: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(legends): extend unified quill legend to all insight charts (#65295)
Sam Pennington2216beed2889
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsxindex 87b8419acd5f..fd13df4e5c8e 100644--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx@@ -4,6 +4,7 @@ import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-liimport userEvent from '@testing-library/user-event'import { BindLogic, Provider } from 'kea'+import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { insightDataLogic } from 'scenes/insights/insightDataLogic'import { insightLogic } from 'scenes/insights/insightLogic'@@ -53,12 +54,20 @@ function makeRetentionQuery(): RetentionQuery {return { kind: NodeKind.RetentionQuery, retentionFilter: {} }}-function makeStickinessQuery(): StickinessQuery {- return { kind: NodeKind.StickinessQuery, series: [...pageviewSeries] }+function makeStickinessQuery(display?: ChartDisplayType): StickinessQuery {+ return {+ kind: NodeKind.StickinessQuery,+ series: [...pageviewSeries],+ stickinessFilter: { display },+ }}function makeLifecycleQuery(): LifecycleQuery {- return { kind: NodeKind.LifecycleQuery, series: [...pageviewSeries] }+ return {+ kind: NodeKind.LifecycleQuery,+ series: [...pageviewSeries],+ lifecycleFilter: { showLegend: true },+ }}function getSectionTitles(): string[] {@@ -350,4 +359,45 @@ describe('InsightDisplayConfig', () => {})})})++ describe('line graph display options with the quill legend flag', () => {+ beforeEach(() => {+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_LEGEND]: true,+ })+ })++ it('keeps the "Show legend" checkbox and adds a position select on the same row', async () => {+ setupAndRender(makeTrendsQuery(ChartDisplayType.ActionsLineGraph))+ await openOptionsMenu()++ const legendItem = getDisplaySectionItems().find((item) => item.includes('Show legend'))+ expect(legendItem).toBeTruthy()+ expect(legendItem).toContain('Bottom')+ })++ it.each([+ ['trends bar', () => makeTrendsQuery(ChartDisplayType.ActionsBar)],+ ['trends unstacked bar', () => makeTrendsQuery(ChartDisplayType.ActionsUnstackedBar)],+ ['stickiness line', () => makeStickinessQuery(ChartDisplayType.ActionsLineGraph)],+ ['stickiness bar', () => makeStickinessQuery(ChartDisplayType.ActionsBar)],+ ['lifecycle', () => makeLifecycleQuery()],+ ])('adds the legend position select for %s', async (_desc, makeQuery) => {+ setupAndRender(makeQuery())+ await openOptionsMenu()++ const legendItem = getDisplaySectionItems().find((item) => item.includes('Show legend'))+ expect(legendItem).toBeTruthy()+ expect(legendItem).toContain('Bottom')+ })++ it('keeps the plain "Show legend" checkbox for the aggregated bar-value chart', async () => {+ setupAndRender(makeTrendsQuery(ChartDisplayType.ActionsBarValue))+ await openOptionsMenu()++ // The aggregated bar-value layout has no in-chart legend, so it must not get a position select.+ const items = getDisplaySectionItems()+ expect(items.some((item) => item.includes('Bottom'))).toBe(false)+ })+ })})diff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsxindex 5aab39478ddc..0ff208fae01b 100644--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx@@ -5,9 +5,7 @@ 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'@@ -136,13 +134,13 @@ export function InsightVizDisplay({useValues(insightLogic)const { activeView } = useValues(insightNavLogic(insightProps))- const { featureFlags } = useValues(featureFlagLogic)const {isFunnels,isPaths,hasDetailedResultsTable,showLegend,+ usesInChartLegend,hasFormula,supportsDisplay,samplingFactor,@@ -287,16 +285,9 @@ 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 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+ // don't render two legends. The slope graph always does; trends/stickiness/lifecycle charts do+ // when the quill in-chart legend is on (`usesInChartLegend`).+ const chartDrawsOwnLegend = display === ChartDisplayType.SlopeGraph || usesInChartLegendconst showSideLegend = supportsDisplay && showLegend && !chartDrawsOwnLegendfunction renderActiveView(): JSX.Element | null {diff --git a/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx b/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsxindex 32b26951c55a..e4a862c3e3b3 100644--- a/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx+++ b/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx@@ -39,6 +39,7 @@ export function useInsightDisplayOptions(): { items: LemonMenuItems; count: numbtrendsFilter,hasLegend,showLegend,+ usesInChartLegend,supportsValueOnSeries,showPercentStackView,supportsPercentStackView,@@ -83,8 +84,9 @@ export function useInsightDisplayOptions(): { items: LemonMenuItems; count: numbconst isBoxPlot = display === ChartDisplayType.BoxPlotconst isCalendarHeatmap = display === ChartDisplayType.CalendarHeatmap// The in-chart quill legend supports placement, so it gets a single "Legend" select (Hide +- // position) instead of the legacy show/hide checkbox.- const useQuillLegendOptions = quillLegendEnabled && isTrends && isLineDisplay+ // position) instead of the legacy show/hide checkbox. `usesInChartLegend` covers+ // trends/stickiness/lifecycle; funnel trends draw their own in-chart legend too.+ const useQuillLegendOptions = usesInChartLegend || (quillLegendEnabled && showFunnelLegendConfig)const showDisplaySection =(isTrends && !isCalendarHeatmap) || isRetention || isTrendsFunnel || isStickiness || isLifecyclediff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 21c1e10edf4b..0a1905e11a34 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -22617,6 +22617,12 @@"$ref": "#/definitions/FunnelLayout","default": "vertical"},+ "legendPosition": {+ "default": "bottom",+ "description": "Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend.",+ "enum": ["top", "bottom", "left", "right"],+ "type": "string"+ },"resultCustomizations": {"additionalProperties": {"$ref": "#/definitions/ResultCustomizationByValue"@@ -25440,6 +25446,12 @@"LifecycleFilter": {"additionalProperties": false,"properties": {+ "legendPosition": {+ "default": "bottom",+ "description": "Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend.",+ "enum": ["top", "bottom", "left", "right"],+ "type": "string"+ },"showLegend": {"default": false,"type": "boolean"@@ -41655,6 +41667,12 @@},"type": "array"},+ "legendPosition": {+ "default": "bottom",+ "description": "Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend.",+ "enum": ["top", "bottom", "left", "right"],+ "type": "string"+ },"resultCustomizationBy": {"$ref": "#/definitions/ResultCustomizationBy","default": "value",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 255e3ae853a0..06923ed07d08 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -1732,6 +1732,9 @@ export type FunnelsFilter = {* @default false*/showLegend?: boolean+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend.+ * @default bottom */+ legendPosition?: 'top' | 'bottom' | 'left' | 'right'/** @default false */showValuesOnSeries?: boolean/** Breakdown table sorting. Format: 'column_key' or '-column_key' (descending) */@@ -1932,6 +1935,9 @@ export interface StickinessCriteria {export type StickinessFilter = {display?: StickinessFilterLegacy['display']showLegend?: StickinessFilterLegacy['show_legend']+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend.+ * @default bottom */+ legendPosition?: 'top' | 'bottom' | 'left' | 'right'showValuesOnSeries?: StickinessFilterLegacy['show_values_on_series']showMultipleYAxes?: StickinessFilterLegacy['show_multiple_y_axes']hiddenLegendIndexes?: integer[]@@ -1951,6 +1957,7 @@ export type StickinessFilter = {export const STICKINESS_FILTER_PROPERTIES = new Set<keyof StickinessFilter>(['display','showLegend',+ 'legendPosition','showValuesOnSeries','hiddenLegendIndexes',])@@ -1997,6 +2004,9 @@ export type LifecycleFilter = {toggledLifecycles?: LifecycleFilterLegacy['toggledLifecycles']/** @default false */showLegend?: LifecycleFilterLegacy['show_legend']+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend.+ * @default bottom */+ legendPosition?: 'top' | 'bottom' | 'left' | 'right'/** @default true */stacked?: boolean}diff --git a/frontend/src/queries/utils.ts b/frontend/src/queries/utils.tsindex da4303e337bd..ef4201669893 100644--- a/frontend/src/queries/utils.ts+++ b/frontend/src/queries/utils.ts@@ -579,6 +579,12 @@ export const getShowLegend = (query: InsightQueryNode): boolean | undefined => {export const getLegendPosition = (query: InsightQueryNode): string | undefined => {if (isTrendsQuery(query)) {return query.trendsFilter?.legendPosition+ } else if (isStickinessQuery(query)) {+ return query.stickinessFilter?.legendPosition+ } else if (isLifecycleQuery(query)) {+ return query.lifecycleFilter?.legendPosition+ } else if (isFunnelsQuery(query)) {+ return query.funnelsFilter?.legendPosition}return undefined}diff --git a/frontend/src/scenes/funnels/funnelDataLogic.ts b/frontend/src/scenes/funnels/funnelDataLogic.tsindex 03417e8ce838..ae6294d3ec69 100644--- a/frontend/src/scenes/funnels/funnelDataLogic.ts+++ b/frontend/src/scenes/funnels/funnelDataLogic.ts@@ -178,6 +178,7 @@ export const funnelDataLogic = kea<funnelDataLogicType>(['insightDataError','getTheme','showLegend',+ 'legendPosition','showValuesOnSeries','hasDataWarehouseSeries','labelGroupType',diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.tsindex 340837d0a82e..aae23ec916a5 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts@@ -114,6 +114,16 @@ import type { insightVizDataLogicType } from './insightVizDataLogicType'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 = [+ ChartDisplayType.ActionsLineGraph,+ ChartDisplayType.ActionsLineGraphCumulative,+ ChartDisplayType.ActionsAreaGraph,+ ChartDisplayType.ActionsBar,+ ChartDisplayType.ActionsUnstackedBar,+]+export type QuerySourceUpdate = Omit<Partial<InsightQueryNode>, 'kind'>export const insightVizDataLogic = kea<insightVizDataLogicType>([@@ -469,6 +479,22 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([!(display && DISPLAY_TYPES_WITHOUT_LEGEND.includes(display)),],+ // Whether the active chart renders the unified in-chart quill legend (replacing the legacy+ // side legend) instead of the legacy show/hide checkbox. Single source of truth shared by+ // InsightDisplayConfig (which control to show) and InsightVizDisplay (suppress side legend).+ usesInChartLegend: [+ (s) => [s.featureFlags, s.isTrends, s.isStickiness, s.isLifecycle, s.display],+ (featureFlags, isTrends, isStickiness, isLifecycle, display): boolean => {+ if (!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_LEGEND]) {+ return false+ }+ if (isLifecycle) {+ return true+ }+ return (isTrends || isStickiness) && (!display || DISPLAYS_WITH_IN_CHART_LEGEND.includes(display))+ },+ ],+hasDetailedResultsTable: [(s) => [s.isTrends, s.isStickiness, s.display],(isTrends: boolean, isStickiness: boolean, display: ChartDisplayType | undefined) =>diff --git a/posthog/schema.py b/posthog/schema.pyindex 89b3fe4a8976..1e6701c09155 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -5512,6 +5512,10 @@ class LifecycleFilter(BaseModel):model_config = ConfigDict(extra="forbid",)+ legendPosition: LegendPosition | None = Field(+ default=LegendPosition.BOTTOM,+ description=("Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend."),+ )showLegend: bool | None = FalseshowPercentagesOnSeries: bool | None = Field(default=None,@@ -7010,6 +7014,10 @@ class StickinessFilter(BaseModel):computedAs: StickinessComputationMode | None = Nonedisplay: ChartDisplayType | None = NonehiddenLegendIndexes: list[int] | None = None+ legendPosition: LegendPosition | None = Field(+ default=LegendPosition.BOTTOM,+ description=("Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend."),+ )resultCustomizationBy: ResultCustomizationBy | None = Field(default=ResultCustomizationBy.VALUE,description=("Whether result datasets are associated by their values or by their order."),@@ -22225,6 +22233,10 @@ class FunnelsFilter(BaseModel):),)layout: FunnelLayout | None = FunnelLayout.VERTICAL+ legendPosition: LegendPosition | None = Field(+ default=LegendPosition.BOTTOM,+ description=("Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend."),+ )resultCustomizations: dict[str, ResultCustomizationByValue] | None = Field(default=None,description="Customizations for the appearance of result datasets.",diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex abfcc92df9fc..9e207f59615f 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -1946,6 +1946,13 @@ class FunnelVizType(StrEnum):FLOW = "flow"+class LegendPosition(StrEnum):+ TOP = "top"+ BOTTOM = "bottom"+ LEFT = "left"+ RIGHT = "right"++class Position(StrEnum):START = "start"END = "end"@@ -3292,13 +3299,6 @@ class DetailedResultsAggregationType(StrEnum):MEDIAN = "median"-class LegendPosition(StrEnum):- TOP = "top"- BOTTOM = "bottom"- LEFT = "left"- RIGHT = "right"--class UsageMetricDisplay(StrEnum):NUMBER = "number"SPARKLINE = "sparkline"diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 068db8d11c2d..d66c865c4d2f 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -2508,6 +2508,8 @@ export interface FunnelsFilterApi {/** Trends only: hide periods whose conversion window has not fully elapsed yet, so the recent tail of the trend isn't dragged down by entrants who still have time to convert. */hideIncompleteConversionWindowPeriods?: boolean | nulllayout?: FunnelLayoutApi | null+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPositionApi | null/** Customizations for the appearance of result datasets. */resultCustomizations?: FunnelsFilterApiResultCustomizations/** Whether to render annotations on the chart. Only applies to historical-trends funnels. */@@ -3107,6 +3109,8 @@ export interface StickinessFilterApi {computedAs?: StickinessComputationModeApi | nulldisplay?: ChartDisplayTypeApi | nullhiddenLegendIndexes?: number[] | null+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPositionApi | null/** Whether result datasets are associated by their values or by their order. */resultCustomizationBy?: ResultCustomizationByApi | null/** Customizations for the appearance of result datasets. */@@ -3182,6 +3186,8 @@ export const LifecycleToggleApi = {} as constexport interface LifecycleFilterApi {+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPositionApi | nullshowLegend?: boolean | null/** Append per-band percentage to each value label (e.g. `580 (42%)`). Requires `showValuesOnSeries` — on its own it has no visible effect. */showPercentagesOnSeries?: boolean | nulldiff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 4ec09a2461ef..81768c9ce921 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -1933,6 +1933,8 @@ export interface FunnelsFilterApi {/** Trends only: hide periods whose conversion window has not fully elapsed yet, so the recent tail of the trend isn't dragged down by entrants who still have time to convert. */hideIncompleteConversionWindowPeriods?: boolean | nulllayout?: FunnelLayoutApi | null+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPositionApi | null/** Customizations for the appearance of result datasets. */resultCustomizations?: FunnelsFilterApiResultCustomizations/** Whether to render annotations on the chart. Only applies to historical-trends funnels. */@@ -2532,6 +2534,8 @@ export interface StickinessFilterApi {computedAs?: StickinessComputationModeApi | nulldisplay?: ChartDisplayTypeApi | nullhiddenLegendIndexes?: number[] | null+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPositionApi | null/** Whether result datasets are associated by their values or by their order. */resultCustomizationBy?: ResultCustomizationByApi | null/** Customizations for the appearance of result datasets. */@@ -2607,6 +2611,8 @@ export const LifecycleToggleApi = {} as constexport interface LifecycleFilterApi {+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPositionApi | nullshowLegend?: boolean | null/** Append per-band percentage to each value label (e.g. `580 (42%)`). Requires `showValuesOnSeries` — on its own it has no visible effect. */showPercentagesOnSeries?: boolean | nulldiff --git a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsx b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsxindex bc409547546f..b38e1355148d 100644--- a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsx+++ b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsx@@ -6,6 +6,8 @@ import { ChartLegend, TimeSeriesLineChart, legendItemsFromSeries } from '@posthoimport type { PointClickData, TimeSeriesLineChartConfig, TooltipConfig, TooltipContext } from '@posthog/quill-charts'import { buildTheme } from 'lib/charts/utils/theme'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'import { funnelPersonsModalLogic } from 'scenes/funnels/funnelPersonsModalLogic'import { hasBreakdown } from 'scenes/funnels/funnelUtils'@@ -69,12 +71,19 @@ export function FunnelLineChart({interval,insightData,showLegend,+ legendPosition,showValuesOnSeries,funnelsFilter,breakdownFilter,labelGroupType,getFunnelsColor,} = useValues(funnelDataLogic(insightProps))+ const { featureFlags } = useValues(featureFlagLogic)+ // The legend has always rendered in-chart here; the flag only adds the configurable placement+ // (defaulting to bottom to match the other in-chart legends). Without the flag it stays at top.+ const legendPlacement = featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_LEGEND]+ ? ((legendPosition as 'top' | 'bottom' | 'left' | 'right') ?? 'bottom')+ : 'top'const { canOpenPersonModal } = useValues(funnelPersonsModalLogic(insightProps))const { timezone, weekStartDay } = useValues(teamLogic)const { allCohorts } = useValues(cohortsModel)@@ -193,7 +202,7 @@ export function FunnelLineChart({<ChartLegendshow={!!showLegend && legendItems.length > 1}items={legendItems}- position="top"+ position={legendPlacement}legendDataAttr="funnel-line-legend"><TimeSeriesLineChart<FunnelSeriesMeta>diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsxindex 2e51b42d3d94..f3be0ba943b7 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx+++ b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx@@ -25,6 +25,7 @@ import {type TrendsSeriesMeta,} from '../../trends/shared/trendsSeriesMeta'import { TrendsTooltip } from '../../trends/shared/TrendsTooltip'+import { useTrendsLegendConfig } from '../../trends/shared/useTrendsLegendConfig'import { handleStickinessChartClick } from '../StickinessLineChart/handleStickinessChartClick'import {buildStickinessLabels,@@ -44,6 +45,9 @@ export function StickinessBarChart({ context }: StickinessBarChartProps): JSX.Elconst theme = useMemo(() => buildTheme(), [])const { insightProps } = useValues(insightLogic)+ const legendConfig = useTrendsLegendConfig({ insightProps })+ const quillLegendEnabled = !!legendConfig+const {indexedResults,display,@@ -78,21 +82,26 @@ export function StickinessBarChart({ context }: StickinessBarChartProps): JSX.El() =>buildStickinessBarSeries<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {getColor: getTrendsColor,- getHidden: getTrendsHidden,+ // With the quill legend on, hidden series stay listed (dimmed) and are excluded via+ // config.legend.hiddenKeys instead of being dropped here, so the legend can restore them.+ getHidden: quillLegendEnabled ? undefined : getTrendsHidden,buildMeta: buildTrendsSeriesMeta,}),- [indexedResults, getTrendsColor, getTrendsHidden]+ [indexedResults, getTrendsColor, getTrendsHidden, quillLegendEnabled])const chartConfig: TimeSeriesBarChartConfig = useMemo(- () =>- buildStickinessBarTimeSeriesConfig({+ () => ({+ ...buildStickinessBarTimeSeriesConfig({yAxisScaleType,isGrouped,valueLabels: showValuesOnSeries ? { formatter: stickinessPercentFormatter } : false,tooltip: STICKINESS_TOOLTIP_CONFIG,}),- [yAxisScaleType, isGrouped, showValuesOnSeries]+ // Interactive legend is a component concern, kept out of the pure transform.+ legend: legendConfig,+ }),+ [yAxisScaleType, isGrouped, showValuesOnSeries, legendConfig])// Close over the primitives so the click memos don't invalidate when unrelateddiff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsxindex d304927252d6..23badcf62ac2 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx@@ -24,6 +24,7 @@ import {type TrendsSeriesMeta,} from '../../trends/shared/trendsSeriesMeta'import { TrendsTooltip } from '../../trends/shared/TrendsTooltip'+import { useTrendsLegendConfig } from '../../trends/shared/useTrendsLegendConfig'import { handleStickinessChartClick } from './handleStickinessChartClick'import {buildStickinessLabels,@@ -44,6 +45,9 @@ export function StickinessLineChart({ context }: StickinessLineChartProps): JSX.const theme = useMemo(() => buildTheme(), [])const { insightProps } = useValues(insightLogic)+ const legendConfig = useTrendsLegendConfig({ insightProps })+ const quillLegendEnabled = !!legendConfig+const {indexedResults,display,@@ -80,21 +84,26 @@ export function StickinessLineChart({ context }: StickinessLineChartProps): JSX.showMultipleYAxes: showMultipleYAxes ?? undefined,display: display ?? undefined,getColor: getTrendsColor,- getHidden: getTrendsHidden,+ // With the quill legend on, hidden series stay listed (dimmed) and are excluded via+ // config.legend.hiddenKeys instead of being dropped here, so the legend can restore them.+ getHidden: quillLegendEnabled ? undefined : getTrendsHidden,buildMeta: buildTrendsSeriesMeta,}),- [indexedResults, display, getTrendsColor, getTrendsHidden, showMultipleYAxes]+ [indexedResults, display, getTrendsColor, getTrendsHidden, showMultipleYAxes, quillLegendEnabled])const chartConfig: TimeSeriesLineChartConfig = useMemo(- () =>- buildStickinessLineTimeSeriesConfig({+ () => ({+ ...buildStickinessLineTimeSeriesConfig({yAxisScaleType,valueLabels: showValuesOnSeries ? { formatter: stickinessPercentFormatter } : false,showCrosshair: true,tooltip: STICKINESS_TOOLTIP_CONFIG,}),- [yAxisScaleType, showValuesOnSeries]+ // Interactive legend is a component concern, kept out of the pure transform.+ legend: legendConfig,+ }),+ [yAxisScaleType, showValuesOnSeries, legendConfig])const canHandleClick = !!context?.onDataPointClick || !!hasPersonsModaldiff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsxindex 78f36d58aa2a..3cf0f2715da5 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx@@ -4,6 +4,8 @@ import { cleanup, fireEvent, screen, waitFor } from '@testing-library/react'import { dimensions, setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'+import { FEATURE_FLAGS } from 'lib/constants'+import { NodeKind } from '~/queries/schema/schema-general'import { buildTrendsQuery, chart, getHogChart, personsModal, renderInsight } from '~/test/insight-testing'import { buildAnnotation } from '~/test/insight-testing/test-data'@@ -695,4 +697,30 @@ describe('TrendsBarChart overlays', () => {)})++ describe('quill in-chart legend (PRODUCT_ANALYTICS_QUILL_LEGEND on)', () => {+ const quillLegendFlag = { [FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_LEGEND]: true }+ const twoSeriesBar = trendsBar({+ series: [+ { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },+ { kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' },+ ],+ trendsFilter: { display: ChartDisplayType.ActionsBar, showLegend: true },+ })++ const getInChartLegend = (container: HTMLElement): HTMLElement =>+ container.querySelector<HTMLElement>('[data-attr="hog-chart-timeseries-bar-legend"]')!++ it('renders the in-chart legend with a row per series', async () => {+ const { container } = renderInsight({ query: twoSeriesBar, featureFlags: quillLegendFlag })++ await waitFor(() => {+ expect(screen.getByRole('img', { name: /chart with 2 data series/i })).toBeInTheDocument()+ })++ const legendEl = getInChartLegend(container)+ expect(legendEl.textContent).toContain('$pageview')+ expect(legendEl.textContent).toContain('Napped')+ })+ })})diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsxindex 1ad8af4900a7..2f108cff19d5 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx@@ -39,6 +39,7 @@ import { TrendsAlertOverlays } from '../shared/TrendsAlertOverlays'import { trendsFilterToYFormatterConfig } from '../shared/trendsAxisFormat'import { buildTrendsSeriesMeta, type TrendsSeriesMeta } from '../shared/trendsSeriesMeta'import { TrendsTooltip } from '../shared/TrendsTooltip'+import { useTrendsLegendConfig } from '../shared/useTrendsLegendConfig'import { getAggregatedDisplayLabel as getAggregatedDisplayLabelFn } from './getAggregatedDisplayLabel'import { handleTrendsBarAggregatedChartClick } from './handleTrendsBarAggregatedChartClick'import {@@ -87,6 +88,10 @@ export function TrendsBarChart({const theme = useMemo(() => buildTheme(), [])const { insightProps, insight } = useValues(insightLogic)+ // Time-series bars (vertical) render the in-chart legend; the aggregated bar-value layout has+ // no legend (each bar is a breakdown row, not a series).+ const legendConfig = useTrendsLegendConfig({ insightProps, inSharedMode })+const {indexedResults,display,@@ -116,6 +121,7 @@ export function TrendsBarChart({const isAggregated = display === ChartDisplayType.ActionsBarValueconst isGrouped = display === ChartDisplayType.ActionsUnstackedBar+ const quillLegendEnabled = !isAggregated && !!legendConfigconst isPercentStackView = !isAggregated && !!showPercentStackView && !!supportsPercentStackView// Per-series y-axes are only meaningful for grouped (unstacked) bars — stacked layouts share// one axis. Mirrors the legacy ActionsLineGraph, which assigns y0/y1/… per dataset.@@ -156,7 +162,9 @@ export function TrendsBarChart({}const timeSeries = buildTrendsBarTimeSeries<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {getColor: getTrendsColor,- getHidden: getTrendsHidden,+ // With the quill legend on, hidden series stay listed (dimmed) and are excluded via+ // config.legend.hiddenKeys instead of being dropped here, so the legend can restore them.+ getHidden: quillLegendEnabled ? undefined : getTrendsHidden,buildMeta: buildTrendsSeriesMeta,showMultipleYAxes: applyMultipleYAxes,})@@ -174,6 +182,7 @@ export function TrendsBarChart({stackBreakdowns,getAggregatedDisplayLabel,applyMultipleYAxes,+ quillLegendEnabled,])const valueLabelFormatter = useCallback(@@ -189,8 +198,8 @@ export function TrendsBarChart({)const timeSeriesConfig: TimeSeriesBarChartConfig = useMemo(- () =>- buildTrendsBarTimeSeriesConfig({+ () => ({+ ...buildTrendsBarTimeSeriesConfig({trendsFilter,baseCurrency,isPercentStackView,@@ -205,6 +214,10 @@ export function TrendsBarChart({valueLabels: showValuesOnSeries ? { formatter: valueLabelFormatter } : false,tooltip: TIME_SERIES_TOOLTIP_CONFIG,}),+ // Interactive legend (toggle callbacks, context menu) is a component concern, kept out+ // of the pure transform so the builder stays free of React state.+ legend: legendConfig,+ }),[trendsFilter,baseCurrency,@@ -219,6 +232,7 @@ export function TrendsBarChart({goalLines,showValuesOnSeries,valueLabelFormatter,+ legendConfig,])diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsxindex 337aff67a63a..876325df421b 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx@@ -6,6 +6,8 @@ import type { PointClickData, TooltipContext } from '@posthog/quill-charts'import { buildTheme } from 'lib/charts/utils/theme'import { getBarColorFromStatus } from 'lib/colors'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'import { InsightEmptyState } from 'scenes/insights/EmptyStates'import { insightLogic } from 'scenes/insights/insightLogic'@@ -65,8 +67,15 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLishowValuesOnSeries,showPercentagesOnSeries,showLegend,+ legendPosition,} = useValues(trendsDataLogic(insightProps))const { timezone, weekStartDay, baseCurrency } = useValues(teamLogic)+ const { featureFlags } = useValues(featureFlagLogic)+ // The legend has always rendered in-chart here; the flag only adds the configurable placement+ // (defaulting to bottom to match the other in-chart legends). Without the flag it stays at top.+ const legendPlacement = featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_LEGEND]+ ? ((legendPosition as 'top' | 'bottom' | 'left' | 'right') ?? 'bottom')+ : 'top'const isStacked = lifecycleFilter?.stacked ?? true@@ -206,7 +215,12 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLiconst annotationsDates = currentPeriodResult?.days ?? []return (- <ChartLegend show={!!showLegend} items={legendItems} position="top" legendDataAttr="trend-lifecycle-legend">+ <ChartLegend+ show={!!showLegend}+ items={legendItems}+ position={legendPlacement}+ legendDataAttr="trend-lifecycle-legend"+ ><TimeSeriesBarChart<TrendsSeriesMeta>series={series}labels={labels}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e7a4290f49ce..58a611f3134a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -2624,6 +2624,8 @@ export namespace Schemas {/** Trends only: hide periods whose conversion window has not fully elapsed yet, so the recent tail of the trend isn't dragged down by entrants who still have time to convert. */hideIncompleteConversionWindowPeriods?: boolean | null;layout?: FunnelLayout | null;+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPosition | null;/** Customizations for the appearance of result datasets. */resultCustomizations?: FunnelsFilterResultCustomizations;/** Whether to render annotations on the chart. Only applies to historical-trends funnels. */@@ -3082,6 +3084,8 @@ export namespace Schemas {computedAs?: StickinessComputationMode | null;display?: ChartDisplayType | null;hiddenLegendIndexes?: number[] | null;+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPosition | null;/** Whether result datasets are associated by their values or by their order. */resultCustomizationBy?: ResultCustomizationBy | null;/** Customizations for the appearance of result datasets. */@@ -3134,6 +3138,8 @@ export namespace Schemas {} as const;export interface LifecycleFilter {+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPosition | null;showLegend?: boolean | null;/** Append per-band percentage to each value label (e.g. `580 (42%)`). Requires `showValuesOnSeries` — on its own it has no visible effect. */showPercentagesOnSeries?: boolean | null;