Skip to content

: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.

feat(insights): add the proportion bar to trends insights behind a flag (#113527)

Paul D'Ambrabae05561b544
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f50ff4947855..79aeb4595692 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2453,9 +2453,9 @@ snapshots:
components-releasestagetag--internal--light:
hash: v1.k794b7964.18c439d8f91e2f463a5212933f502cd084ac8c4d796963ba7ff8c8946e4cc5fb.uEErXKcQANzO8ov9EwNwoFS-YcmeCWkxYTTAkQkRRoE
components-sample-data-state--all-variants--dark:
- hash: v1.k794b7964.f07ee511a2c77a4ff5a2ed0ca5030e3e57656ade775012ea85bd9c5047f29d3f.297btInaIUjNnmRtmJbS5ZyTmlux9j6wO8NlDAevNzo
+ hash: v1.k794b7964.f78ff2e4dfb88eb594e79cfd2946658b5cf762d48f60586fc52ca5cfa5edae93.lTPuhty3xFx4X4LZxMSTIGchYb4cDBus5_GB8-pQa6w
components-sample-data-state--all-variants--light:
- hash: v1.k794b7964.ebd4fc5add8fbb45cfe382af5aa48568c9f094574ab6e2088566a75bd3e1762a.a_1stky_5F9h4knpDr1JpdwhATEe7sdMLbVhOdHrkok
+ hash: v1.k794b7964.0c07edc11002b2ce97bc1d9ade124e890d09f6ac320be361fa69734a57d883a0.ZC5gGxbcfhBg7mb3LwAxEd1U3BsR21JB6_M8MKW6xx8
components-sample-data-state--with-setup-pull-request--dark:
hash: v1.k794b7964.a7647c826dc90cc8f49595664f6da4e08b6a623c018b67413168e7a423ea4e5b.zYzBM5U_KBYjVXH7MR_BUlxgJuH6t6IMTcDtgmwn_rQ
components-sample-data-state--with-setup-pull-request--light:
@@ -4076,6 +4076,10 @@ snapshots:
hash: v1.k794b7964.9b44378c8b23c54996de740b079e0029d0a474c9ca7f977b7d7aab07eece7f8e.DH5BI-XTKBTeGu8xAITjb7Ktz0BulqIqgPauao-MDpU
insights-trendspiechart--min-height-parent--light:
hash: v1.k794b7964.cd52243e5d45d2eb6397a1efffcb6b6c9a5f98ef4a265fab0abc5974c69c0999.17OfM6Hht52excrKELBhQIdviX7ue6tytC6UMA-KrMk
+ insights-trendsproportionbar--breakdown--dark:
+ hash: v1.k794b7964.6eceb86d55858fdfcb7b0778761f04d4fe14cff1cd91a563fb00aad4d75a95ea.dmjiMUb3sMfWqVZIPvgaBSWWRObrwTNbPgXQxGdliMI
+ insights-trendsproportionbar--breakdown--light:
+ hash: v1.k794b7964.218468e49e9f777c32906da033cab6e01fc5fa2ee6dae4da61c911a99d3e8382.SOSY_WwQDGCd7mrUgtwWXoN4SVhSJSRRfcaBcTGxBH0
insights-trendsslopechart--default--dark:
hash: v1.k794b7964.f843b256c76c813e822e3c899d5bb4302f8970671422576d82eab10dba5cec17.QicU0ACrmlNYm9zJKICNpTr7h41TZAYTe4xNsHoy2so
insights-trendsslopechart--default--light:
diff --git a/frontend/src/lib/components/ChartFilter/ChartFilter.tsx b/frontend/src/lib/components/ChartFilter/ChartFilter.tsx
index 9d11a48a0a92..a55c448ff33a 100644
--- a/frontend/src/lib/components/ChartFilter/ChartFilter.tsx
+++ b/frontend/src/lib/components/ChartFilter/ChartFilter.tsx
@@ -45,7 +45,7 @@ export function ChartFilter({
onOpen?: () => void
}): JSX.Element {
const { insightProps, editingDisabledReason } = useValues(insightLogic)
- const { display } = useValues(insightVizDataLogic(insightProps))
+ const { display, compareFilter } = useValues(insightVizDataLogic(insightProps))
const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))
const { featureFlags } = useValues(featureFlagLogic)
@@ -60,6 +60,9 @@ export function ChartFilter({
breakdowns: breakdownFilter?.breakdowns,
boxPlotMissingProperty: isBoxPlotMissingProperty(series as TrendsQuery['series']),
hasMetricInsight: !!featureFlags[FEATURE_FLAGS.METRIC_INSIGHT],
+ hasProportionBarChart: !!featureFlags[FEATURE_FLAGS.PROPORTION_BAR_CHART],
+ currentDisplay: display ?? undefined,
+ isComparing: !!compareFilter?.compare,
}).map((group) => ({ title: group.title, options: group.options.map(chartDisplayOptionToSelectOption) }))
return (
diff --git a/frontend/src/lib/components/InsightLegend/InsightLegendRow.tsx b/frontend/src/lib/components/InsightLegend/InsightLegendRow.tsx
index 06fd8a29e537..419af134cc00 100644
--- a/frontend/src/lib/components/InsightLegend/InsightLegendRow.tsx
+++ b/frontend/src/lib/components/InsightLegend/InsightLegendRow.tsx
@@ -5,7 +5,7 @@ import { getSeriesBackgroundColor } from 'lib/colors'
import { captureLegendMenuAction } from 'lib/components/ChartLegendSeriesMenu/captureLegendMenuAction'
import { ChartLegendSeriesMenu } from 'lib/components/ChartLegendSeriesMenu/ChartLegendSeriesMenu'
import { InsightLabel } from 'lib/components/InsightLabel'
-import { PIE_DISPLAY_TYPES } from 'lib/constants'
+import { PART_OF_WHOLE_DISPLAY_TYPES } from 'lib/constants'
import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { insightLogic } from 'scenes/insights/insightLogic'
@@ -113,7 +113,7 @@ export function InsightLegendRow({ item, readOnly = false }: InsightLegendRowPro
disabledReason={!canEditInsight ? 'You need editor access to modify this insight.' : undefined}
/>
</div>
- {display && PIE_DISPLAY_TYPES.includes(display) && (
+ {display && PART_OF_WHOLE_DISPLAY_TYPES.includes(display) && (
<div className="text-secondary grow-0">
{formatAggregationAxisValue(trendsFilter, item.aggregated_value, baseCurrency)}
</div>
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx
index df26d06796d9..d2ecff6c62e1 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx
@@ -351,6 +351,23 @@ describe('InsightDisplayConfig', () => {
await openOptionsMenu()
expect(getTabLabels()).toEqual(['General', 'Axes', 'Lines'])
})
+
+ it.each([
+ ['a proportion bar the user left alone', ChartDisplayType.ActionsProportionBar, {}, 0],
+ [
+ 'a proportion bar with its legend turned off',
+ ChartDisplayType.ActionsProportionBar,
+ { showLegend: false },
+ 1,
+ ],
+ ['a line chart with its legend turned on', ChartDisplayType.ActionsLineGraph, { showLegend: true }, 1],
+ ])('counts the legend as changed only for %s', (_name, display, trendsFilter, expected) => {
+ setupAndRender(makeTrendsQuery(display, trendsFilter))
+
+ expect(screen.getAllByLabelText('Options')[0].textContent ?? '').toMatch(
+ expected ? new RegExp(`\\(${expected}\\)`) : /^[^(]*$/
+ )
+ })
})
describe('overlays tab', () => {
diff --git a/frontend/src/queries/nodes/InsightViz/InsightViz.scss b/frontend/src/queries/nodes/InsightViz/InsightViz.scss
index a3a184841e77..009876074971 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightViz.scss
+++ b/frontend/src/queries/nodes/InsightViz/InsightViz.scss
@@ -311,7 +311,8 @@
.InsightCard__viz--ActionsAreaGraph,
.InsightCard__viz--ActionsBar,
.InsightCard__viz--ActionsUnstackedBar,
- .InsightCard__viz--ActionsPie {
+ .InsightCard__viz--ActionsPie,
+ .InsightCard__viz--ActionsProportionBar {
height: calc(100vh - 8rem);
}
}
diff --git a/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx b/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx
index d4032cea5300..4f4fdfa7c2fd 100644
--- a/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx
+++ b/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx
@@ -3,7 +3,7 @@ import { useValues } from 'kea'
import { normalizeAxisLabel } from '@posthog/quill-charts'
import { smoothingOptions } from 'lib/components/SmoothingFilter/smoothings'
-import { PIE_DISPLAY_TYPES } from 'lib/constants'
+import { PART_OF_WHOLE_DISPLAY_TYPES, PIE_DISPLAY_TYPES } from 'lib/constants'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
@@ -104,6 +104,7 @@ export function useInsightDisplayOptions(): { tabs: DisplayOptionTab[]; count: n
const showFunnelLegendConfig = isTrendsFunnel && hasBreakdownFilter(breakdownFilter)
const isCalendarHeatmap = display === ChartDisplayType.CalendarHeatmap
const isPie = !!display && PIE_DISPLAY_TYPES.includes(display)
+ const isPartOfWhole = !!display && PART_OF_WHOLE_DISPLAY_TYPES.includes(display)
// Percent stacking swaps the raw values out for percentages, so there is no unit left to pick.
// A pie is the exception: it can show the value and the percentage together.
const showsRawValues = !showPercentStackView || (isPie && !!showValuesOnSeries)
@@ -172,7 +173,10 @@ export function useInsightDisplayOptions(): { tabs: DisplayOptionTab[]; count: n
displayItems.push(DisplayOptions.Legend)
}
if (isPie) {
- displayItems.push(DisplayOptions.SliceNames, DisplayOptions.PieTotal)
+ displayItems.push(DisplayOptions.SliceNames)
+ }
+ if (isPartOfWhole) {
+ displayItems.push(DisplayOptions.PieTotal)
}
if (isTrendsFunnel && !hideContinuousChartOptions) {
displayItems.push(DisplayOptions.HideIncompleteFunnelPeriods)
@@ -306,13 +310,16 @@ export function useInsightDisplayOptions(): { tabs: DisplayOptionTab[]; count: n
const unitIsSet =
showUnit && !!trendsFilter?.aggregationAxisFormat && trendsFilter.aggregationAxisFormat !== 'numeric'
+ // A proportion bar shows its legend by default, so only the user's own choice counts as a change.
+ const legendIsChanged =
+ display === ChartDisplayType.ActionsProportionBar ? trendsFilter?.showLegend !== undefined : showLegend
const displayCount = countTruthy(
supportsValueOnSeries && showValuesOnSeries,
isLifecycle && showPercentagesOnSeries,
showPercentStackView,
isPie && trendsFilter?.showLabelsOnSeries,
unitIsSet,
- (hasLegend || showFunnelLegendConfig) && showLegend,
+ (hasLegend || showFunnelLegendConfig) && legendIsChanged,
showAnnotationsConfig && (showAnnotations === false || !!annotationsScope),
isMetric && trendsFilter?.metricShowChange === false,
isMetric && trendsFilter?.metricColorByDirection,
diff --git a/frontend/src/queries/utils.test.ts b/frontend/src/queries/utils.test.ts
index f6d4600865d2..a0ecdbcfdefa 100644
--- a/frontend/src/queries/utils.test.ts
+++ b/frontend/src/queries/utils.test.ts
@@ -17,6 +17,7 @@ import {
escapeHogQLString,
escapePropertyAsHogQLIdentifier,
getDisplay,
+ getShowLegend,
hogql,
isMetricInsightQuery,
queryUsesDataWarehouse,
@@ -241,6 +242,24 @@ describe('convertDataTableNodeToDataVisualizationNode', () => {
})
})
+describe('getShowLegend', () => {
+ const trends = (display: ChartDisplayType, showLegend?: boolean): InsightQueryNode => ({
+ kind: NodeKind.TrendsQuery,
+ series: [],
+ trendsFilter: { display, showLegend },
+ })
+
+ it.each([
+ ['a proportion bar with few parts', trends(ChartDisplayType.ActionsProportionBar), 5, true],
+ ['a proportion bar with many parts', trends(ChartDisplayType.ActionsProportionBar), 25, undefined],
+ ['a proportion bar before its parts load', trends(ChartDisplayType.ActionsProportionBar), undefined, undefined],
+ ['a proportion bar with the legend turned off', trends(ChartDisplayType.ActionsProportionBar, false), 5, false],
+ ['a line chart', trends(ChartDisplayType.ActionsLineGraph), 5, undefined],
+ ])('%s', (_name, query, partCount, expected) => {
+ expect(getShowLegend(query, partCount)).toBe(expected)
+ })
+})
+
describe('supportsBarValueStacking', () => {
const breakdown = { breakdown: '$browser', breakdown_type: 'event' as const }
const trends = (display: ChartDisplayType, withBreakdown: boolean): InsightQueryNode =>
diff --git a/frontend/src/queries/utils.ts b/frontend/src/queries/utils.ts
index 7d525275100c..cabe18caf7bb 100644
--- a/frontend/src/queries/utils.ts
+++ b/frontend/src/queries/utils.ts
@@ -1,5 +1,5 @@
import { TaxonomicFilterGroupType, TaxonomicFilterValue } from 'lib/components/TaxonomicFilter/types'
-import { PERCENT_STACK_VIEW_DISPLAY_TYPE } from 'lib/constants'
+import { MAX_DEFAULT_PROPORTION_LEGEND_PARTS, PERCENT_STACK_VIEW_DISPLAY_TYPE } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { getAppContext } from 'lib/utils/getAppContext'
@@ -650,11 +650,16 @@ export const getAggregationGroupTypeIndex = (query: InsightQueryNode): GroupType
return undefined
}
-export const getShowLegend = (query: InsightQueryNode): boolean | undefined => {
+const isProportionBarQuery = (query: TrendsQuery): boolean =>
+ query.trendsFilter?.display === ChartDisplayType.ActionsProportionBar
+
+export const getShowLegend = (query: InsightQueryNode, partCount?: number): boolean | undefined => {
if (isStickinessQuery(query)) {
return query.stickinessFilter?.showLegend
} else if (isTrendsQuery(query)) {
- return query.trendsFilter?.showLegend
+ const showsByDefault =
+ isProportionBarQuery(query) && partCount !== undefined && partCount <= MAX_DEFAULT_PROPORTION_LEGEND_PARTS
+ return query.trendsFilter?.showLegend ?? (showsByDefault ? true : undefined)
} else if (isLifecycleQuery(query)) {
return query.lifecycleFilter?.showLegend
} else if (isFunnelsQuery(query)) {
@@ -667,7 +672,7 @@ export const getShowLegend = (query: InsightQueryNode): boolean | undefined => {
// serialize an inline string-literal union and emits a broken type; consumers narrow as needed.
export const getLegendPosition = (query: InsightQueryNode): string | undefined => {
if (isTrendsQuery(query)) {
- return query.trendsFilter?.legendPosition
+ return query.trendsFilter?.legendPosition ?? (isProportionBarQuery(query) ? 'bottom' : undefined)
} else if (isStickinessQuery(query)) {
return query.stickinessFilter?.legendPosition
} else if (isLifecycleQuery(query)) {
diff --git a/frontend/src/scenes/insights/EmptyStates/SampleDataState.stories.tsx b/frontend/src/scenes/insights/EmptyStates/SampleDataState.stories.tsx
index d6b5fedde099..9ba611331c9c 100644
--- a/frontend/src/scenes/insights/EmptyStates/SampleDataState.stories.tsx
+++ b/frontend/src/scenes/insights/EmptyStates/SampleDataState.stories.tsx
@@ -4,7 +4,7 @@ import { mswDecorator } from '~/mocks/browser'
import { SampleDataState, SampleDataVariant } from './SampleDataState'
-const VARIANTS: SampleDataVariant[] = ['line', 'bar', 'pie', 'funnel', 'number', 'table']
+const VARIANTS: SampleDataVariant[] = ['line', 'bar', 'pie', 'proportionBar', 'funnel', 'number', 'table']
const meta: Meta<typeof SampleDataState> = {
component: SampleDataState,
diff --git a/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx b/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx
index 440fa2733d1d..c4c621b66e82 100644
--- a/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx
+++ b/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx
@@ -6,8 +6,14 @@ import { useEffect, useState } from 'react'
import { TextMorph } from 'torph/react'
import { LemonButton, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'
-import { BarChart, LineChart, PieChart } from '@posthog/quill-charts'
-import type { BarChartConfig, LineChartConfig, PieChartConfig, Series } from '@posthog/quill-charts'
+import { BarChart, LineChart, PieChart, ProportionBar } from '@posthog/quill-charts'
+import type {
+ BarChartConfig,
+ LineChartConfig,
+ PieChartConfig,
+ ProportionBarConfig,
+ Series,
+} from '@posthog/quill-charts'
import { useChartTheme } from 'lib/charts/hooks'
import { CommandBlock } from 'lib/components/CommandBlock/CommandBlock'
@@ -17,7 +23,7 @@ import { humanFriendlyNumber } from 'lib/utils/numbers'
import { setupWizardStatusLogic } from 'scenes/onboarding/shared/setupWizardStatusLogic'
import { useWizardCommand } from 'scenes/onboarding/shared/useWizardCommand'
-export type SampleDataVariant = 'line' | 'bar' | 'pie' | 'funnel' | 'number' | 'table'
+export type SampleDataVariant = 'line' | 'bar' | 'pie' | 'proportionBar' | 'funnel' | 'number' | 'table'
const WEEK_LABELS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
const LINE_SERIES: Series[] = [
@@ -49,6 +55,7 @@ const NO_TOOLTIP = { enabled: false } as const
const LINE_CONFIG: LineChartConfig = { showGrid: true, showCrosshair: true, tooltip: NO_TOOLTIP }
const BAR_CONFIG: BarChartConfig = { barCornerRadius: 2, tooltip: NO_TOOLTIP }
const PIE_CONFIG: PieChartConfig = { tooltip: NO_TOOLTIP }
+const PROPORTION_BAR_CONFIG: ProportionBarConfig = { tooltip: NO_TOOLTIP, legend: { show: false } }
function SampleNumber({ animate }: { animate: boolean }): JSX.Element {
const [valueIndex, setValueIndex] = useState(0)
@@ -123,6 +130,8 @@ function SampleChart({ variant }: { variant: Exclude<SampleDataVariant, 'number'
<BarChart series={BAR_SERIES} labels={WEEK_LABELS} theme={theme} config={BAR_CONFIG} />
) : variant === 'funnel' ? (
<BarChart series={FUNNEL_SERIES} labels={FUNNEL_LABELS} theme={theme} config={BAR_CONFIG} />
+ ) : variant === 'proportionBar' ? (
+ <ProportionBar series={PIE_SERIES} theme={theme} config={PROPORTION_BAR_CONFIG} />
) : (
<PieChart series={PIE_SERIES} theme={theme} config={PIE_CONFIG} />
)}
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.test.ts b/frontend/src/scenes/insights/insightVizDataLogic.test.ts
index e39ac4b83252..b8e0ef51b1f6 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.test.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.test.ts
@@ -1232,6 +1232,30 @@ describe('insightVizDataLogic', () => {
})
})
+ describe('showLegend', () => {
+ const rows = (count: number, compare_label?: string): Record<string, any>[] =>
+ Array.from({ length: count }, (_, i) => ({ breakdown_value: `part ${i}`, compare_label }))
+
+ it.each([
+ ['a proportion bar with few parts', rows(15), true],
+ ['a proportion bar with many parts', rows(25), undefined],
+ [
+ 'a proportion bar saved with compare on, counting only the current period',
+ [...rows(15, 'current'), ...rows(15, 'previous')],
+ true,
+ ],
+ ])('%s', async (_name, result, expected) => {
+ builtInsightVizDataLogic.actions.updateQuerySource({
+ ...trendsQueryDefault,
+ trendsFilter: { display: ChartDisplayType.ActionsProportionBar },
+ } as TrendsQuery)
+
+ await expectLogic(builtInsightVizDataLogic, () => {
+ builtInsightDataLogic.actions.loadDataSuccess({ result })
+ }).toMatchValues({ showLegend: expected })
+ })
+ })
+
describe('supportsCompare', () => {
const setFunnelVizType = (funnelVizType: FunnelVizType): void => {
builtInsightVizDataLogic.actions.updateQuerySource({
@@ -1251,6 +1275,18 @@ describe('insightVizDataLogic', () => {
expect(builtInsightVizDataLogic.values.supportsCompare).toBe(expected)
})
+
+ it.each([
+ [ChartDisplayType.ActionsPie, true],
+ [ChartDisplayType.ActionsProportionBar, false],
+ ])('trends %s display -> %s', (display, expected) => {
+ builtInsightVizDataLogic.actions.updateQuerySource({
+ ...trendsQueryDefault,
+ trendsFilter: { display },
+ } as TrendsQuery)
+
+ expect(builtInsightVizDataLogic.values.supportsCompare).toBe(expected)
+ })
})
describe('allEventNames', () => {
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.ts
index 706e15d7bdc6..79b947ec2529 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts
@@ -177,8 +177,22 @@ export const DISPLAYS_WITH_IN_CHART_LEGEND = [
ChartDisplayType.ActionsUnstackedBar,
ChartDisplayType.ActionsPie,
ChartDisplayType.ActionsDonut,
+ ChartDisplayType.ActionsProportionBar,
]
+/** The parts a proportion bar draws: one per result row, leaving out a previous period saved with compare on. */
+function proportionBarPartCount(query: InsightQueryNode, insightData: Record<string, any> | null): number | undefined {
+ const result = insightData?.result
+ if (
+ !isTrendsQuery(query) ||
+ query.trendsFilter?.display !== ChartDisplayType.ActionsProportionBar ||
+ !Array.isArray(result)
+ ) {
+ return undefined
+ }
+ return result.reduce((count: number, row) => (row?.compare_label === 'previous' ? count : count + 1), 0)
+}
+
// Omit must distribute over the query-node union: a plain Omit would collapse the update type
// to the keys shared by every insight kind, dropping fields like samplingFactor that only some have
type DistributiveOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never
@@ -893,7 +907,8 @@ export interface insightVizDataLogicMeta {
| TrendsQuery
| WebOverviewQuery
| WebStatsTableQuery
- | null
+ | null,
+ insightData: Record<string, any>
) => boolean | null | undefined
legendPosition: (
querySource:
@@ -1640,7 +1655,11 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([
return false
}
if (isTrendsQuery(q) || isStickinessQuery(q) || isWebAnalyticsInsightQuery(q)) {
- return display !== ChartDisplayType.WorldMap && display !== ChartDisplayType.CalendarHeatmap
+ return (
+ display !== ChartDisplayType.WorldMap &&
+ display !== ChartDisplayType.CalendarHeatmap &&
+ display !== ChartDisplayType.ActionsProportionBar
+ )
}
// Funnel compare is supported for the STEPS, TRENDS and TIME_TO_CONVERT viz modes.
// FLOW is excluded — the backend ignores compare for it (mirrors `_is_compare_active`).
@@ -1878,7 +1897,7 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([
(querySource: InsightQueryNode | null) => (querySource ? getAnnotationsScope(querySource) : null),
],
showLegend: [
- (s) => [s.querySource],
+ (s) => [s.querySource, s.insightData],
(
q:
| FunnelsQuery
@@ -1889,8 +1908,9 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([
| null
| import('~/queries/schema/schema-general').PathsQuery
| import('~/queries/schema/schema-general').WebOverviewQuery
- | import('~/queries/schema/schema-general').WebStatsTableQuery
- ) => (q ? getShowLegend(q) : null),
+ | import('~/queries/schema/schema-general').WebStatsTableQuery,
+ insightData: Record<string, any> | null
+ ) => (q ? getShowLegend(q, proportionBarPartCount(q, insightData)) : null),
],
legendPosition: [
(s) => [s.querySource],
diff --git a/frontend/src/test/insight-testing/test-data.ts b/frontend/src/test/insight-testing/test-data.ts
index 61aab3cbbf1d..ef1c9e5a483c 100644
--- a/frontend/src/test/insight-testing/test-data.ts
+++ b/frontend/src/test/insight-testing/test-data.ts
@@ -117,6 +117,18 @@ export const trendsSeries = {
{ label: 'Conker', data: [0, 0, 0, 0, 0], days, labels, breakdown_value: 'Conker' },
{ label: 'Prickles', data: [0, 0, 1, 1, 0], days, labels, breakdown_value: 'Prickles' },
] satisfies CannedSeries[],
+ // A part that sums negative, as a trends formula like `A - B` can.
+ napsByHedgehogWithNegativePart: [
+ { label: 'Spike', data: [10, 0, 0, 0, 0], days, labels, breakdown_value: 'Spike' },
+ { label: 'Bramble', data: [-4, 0, 0, 0, 0], days, labels, breakdown_value: 'Bramble' },
+ ] satisfies CannedSeries[],
+ napsByManyHedgehogs: Array.from({ length: 21 }, (_, i) => ({
+ label: `Hedgehog ${i + 1}`,
+ data: [1, 0, 0, 0, 0],
+ days,
+ labels,
+ breakdown_value: `Hedgehog ${i + 1}`,
+ })) satisfies CannedSeries[],
pageviewsByHedgehog: [
{ label: 'Spike', data: [30, 50, 90, 140, 60], days, labels, breakdown_value: 'Spike' },
{ label: 'Bramble', data: [15, 32, 44, 70, 35], days, labels, breakdown_value: 'Bramble' },
@@ -181,6 +193,18 @@ const seriesByEvent: Record<string, EventSeriesConfig> = {
hedgehog: trendsSeries.napsByHedgehog,
},
},
+ NappedWithNegativePart: {
+ default: trendsSeries.napped,
+ breakdowns: {
+ hedgehog: trendsSeries.napsByHedgehogWithNegativePart,
+ },
+ },
+ NappedByManyHedgehogs: {
+ default: trendsSeries.napped,
+ breakdowns: {
+ hedgehog: trendsSeries.napsByManyHedgehogs,
+ },
+ },
ZeroCounts: { default: trendsSeries.withZeroCounts[0], multi: trendsSeries.withZeroCounts },
Minimal: { default: trendsSeries.minimal },
NoActivity: { default: trendsSeries.noActivity },
diff --git a/products/product_analytics/frontend/insights/chartAlternatives/ChartAlternatives.test.tsx b/products/product_analytics/frontend/insights/chartAlternatives/ChartAlternatives.test.tsx
index 3b272b84a9bd..7d6c65c75786 100644
--- a/products/product_analytics/frontend/insights/chartAlternatives/ChartAlternatives.test.tsx
+++ b/products/product_analytics/frontend/insights/chartAlternatives/ChartAlternatives.test.tsx
@@ -113,6 +113,15 @@ describe('ChartAlternatives', () => {
expect(chartPreviewsLogic.findMounted({ embedded: false, ...insightProps })).not.toBeUndefined()
})
+ it('keeps a saved proportion bar as the current chart type while its flag is off', () => {
+ setQuery(makeTrendsQuery({ trendsFilter: { display: ChartDisplayType.ActionsProportionBar } }))
+ const logic = chartAlternativesLogic({ embedded: false, ...insightProps })
+ logic.mount()
+
+ expect(logic.values.currentOption).toMatchObject({ label: 'Proportion bar', icon: 'proportionBar' })
+ logic.unmount()
+ })
+
it('opens the gallery in a popover anchored to the chart type button', async () => {
setQuery(makeTrendsQuery())
const logic = alternativesLogic()
diff --git a/products/product_analytics/frontend/insights/chartAlternatives/ChartDisplayIcon.tsx b/products/product_analytics/frontend/insights/chartAlternatives/ChartDisplayIcon.tsx
index f5d7622a7932..8c4506f011ad 100644
--- a/products/product_analytics/frontend/insights/chartAlternatives/ChartDisplayIcon.tsx
+++ b/products/product_analytics/frontend/insights/chartAlternatives/ChartDisplayIcon.tsx
@@ -5,6 +5,7 @@ import {
IconAreaChart,
IconCumulativeChart,
IconDonutChart,
+ IconProportionBarChart,
IconTableChart,
IconTrendingUp,
} from 'lib/lemon-ui/icons'
@@ -33,6 +34,8 @@ export function ChartDisplayIcon({ icon }: { icon: ChartDisplayIconKind }): JSX.
return <Icon123 />
case 'pie':
return <IconPieChart />
+ case 'proportionBar':
+ return <IconProportionBarChart />
case 'table':
return <IconTableChart />
case 'worldMap':
diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartAlternativesLogic.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartAlternativesLogic.ts
index acd918ae35ba..afa61629c14f 100644
--- a/products/product_analytics/frontend/insights/chartAlternatives/chartAlternativesLogic.ts
+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartAlternativesLogic.ts
@@ -141,7 +141,8 @@ export interface chartAlternativesLogicMeta {
isSingleSeriesOutput: boolean,
trendsSource: TrendsQuery | null,
series: (AnyEntityNode<AnyDataWarehouseNode> | GroupNode<DataWarehouseNode>)[] | null | undefined,
- featureFlags: FeatureFlagsSet
+ featureFlags: FeatureFlagsSet,
+ currentDisplay: ChartDisplayType
) => ChartDisplayOptionGroup[]
alternatives: (options: ChartDisplayOptionGroup[], trendsSource: TrendsQuery | null) => ChartDisplayOption[]
currentOption: (
@@ -230,13 +231,14 @@ export const chartAlternativesLogic = kea<chartAlternativesLogicType>([
): TrendsQuery | null => (querySource && isTrendsQuery(querySource) ? querySource : null),
],
options: [
- (s) => [s.isTrends, s.isSingleSeriesOutput, s.trendsSource, s.series, s.featureFlags],
+ (s) => [s.isTrends, s.isSingleSeriesOutput, s.trendsSource, s.series, s.featureFlags, s.currentDisplay],
(
isTrends: boolean,
isSingleSeriesOutput: boolean,
trendsSource: TrendsQuery | null,
series: (AnyEntityNode<AnyDataWarehouseNode> | GroupNode<DataWarehouseNode>)[] | null | undefined,
- featureFlags: FeatureFlagsSet
+ featureFlags: FeatureFlagsSet,
+ currentDisplay: ChartDisplayType
): ChartDisplayOptionGroup[] =>
getChartDisplayOptions({
isTrends,
@@ -246,6 +248,9 @@ export const chartAlternativesLogic = kea<chartAlternativesLogicType>([
breakdowns: trendsSource?.breakdownFilter?.breakdowns,
boxPlotMissingProperty: isBoxPlotMissingProperty(series as TrendsQuery['series']),
hasMetricInsight: !!featureFlags[FEATURE_FLAGS.METRIC_INSIGHT],
+ hasProportionBarChart: !!featureFlags[FEATURE_FLAGS.PROPORTION_BAR_CHART],
+ currentDisplay,
+ isComparing: !!trendsSource?.compareFilter?.compare,
}),
],
alternatives: [
diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.test.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.test.ts
index d841d5a99073..67f81c2e8a81 100644
--- a/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.test.ts
+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.test.ts
@@ -9,6 +9,7 @@ const RENDERS_EVERYTHING: ChartDisplayOptionEligibility = {
hasTrendsFormula: false,
boxPlotMissingProperty: false,
hasMetricInsight: false,
+ hasProportionBarChart: false,
}
function disabledReasons(eligibility: ChartDisplayOptionEligibility): Map<ChartDisplayType, string | undefined> {
@@ -79,6 +80,22 @@ describe('getChartDisplayOptions', () => {
undefined,
],
['nothing in the way', RENDERS_EVERYTHING, ChartDisplayType.ActionsLineGraph, undefined],
+ [
+ 'a saved insight already using proportion bar while its flag is off',
+ {
+ ...RENDERS_EVERYTHING,
+ hasProportionBarChart: false,
+ currentDisplay: ChartDisplayType.ActionsProportionBar,
+ },
+ ChartDisplayType.ActionsProportionBar,
+ "This type isn't available yet.",
+ ],
+ [
+ 'comparing to a previous period',
+ { ...RENDERS_EVERYTHING, hasProportionBarChart: true, isComparing: true },
+ ChartDisplayType.ActionsProportionBar,
+ "This type doesn't support comparing to a previous period.",
+ ],
])('says why %s disables a chart type', (_case, eligibility, display, disabledReason) => {
const reasons = disabledReasons(eligibility)
@@ -87,11 +104,24 @@ describe('getChartDisplayOptions', () => {
})
it.each([
- [true, true],
- [false, false],
- ])('offers the metric chart type only behind its flag (%s)', (hasMetricInsight, isOffered) => {
- expect(disabledReasons({ ...RENDERS_EVERYTHING, hasMetricInsight }).has(ChartDisplayType.Metric)).toBe(
- isOffered
- )
- })
+ ['hasMetricInsight', ChartDisplayType.Metric, true, undefined, true],
+ ['hasMetricInsight', ChartDisplayType.Metric, false, undefined, false],
+ ['hasProportionBarChart', ChartDisplayType.ActionsProportionBar, true, undefined, true],
+ ['hasProportionBarChart', ChartDisplayType.ActionsProportionBar, false, undefined, false],
+ [
+ 'hasProportionBarChart',
+ ChartDisplayType.ActionsProportionBar,
+ false,
+ ChartDisplayType.ActionsProportionBar,
+ true,
+ ],
+ ['hasProportionBarChart', ChartDisplayType.ActionsProportionBar, false, ChartDisplayType.ActionsPie, false],
+ ] as const)(
+ 'behind %s, offers %s with the flag %s and current display %s: %s',
+ (flag, display, flagEnabled, currentDisplay, offered) => {
+ expect(disabledReasons({ ...RENDERS_EVERYTHING, [flag]: flagEnabled, currentDisplay }).has(display)).toBe(
+ offered
+ )
+ }
+ )
})
diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.ts
index 28b64ac67c7a..925d6acfc8cb 100644
--- a/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.ts
+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.ts
@@ -14,6 +14,7 @@ export type ChartDisplayIcon =
| 'metric'
| 'number'
| 'pie'
+ | 'proportionBar'
| 'table'
| 'worldMap'
@@ -34,11 +35,19 @@ export interface ChartDisplayOptionGroup {
export interface ChartDisplayOptionEligibility {
boxPlotMissingProperty: boolean
hasMetricInsight: boolean
+ hasProportionBarChart: boolean
hasSingleSeriesOutput: boolean
hasTrendsFormula: boolean
isTrends: boolean
breakdown?: BreakdownFilter['breakdown']
breakdowns?: BreakdownFilter['breakdowns']
+ currentDisplay?: ChartDisplayType
+ isComparing?: boolean
+}
+
+/** A chart saved as a proportion bar keeps its own label and icon in the picker while the flag is off. */
+export function offersProportionBar(hasProportionBarChart: boolean, currentDisplay?: ChartDisplayType | null): boolean {
+ return hasProportionBarChart || currentDisplay === ChartDisplayType.ActionsProportionBar
}
const COUNTRY_PROPERTIES = new Set(['$geoip_country_code', '$geoip_country_name'])
@@ -88,11 +97,14 @@ export function applyChartDisplay(query: TrendsQuery, display: ChartDisplayType)
export function getChartDisplayOptions({
boxPlotMissingProperty,
hasMetricInsight,
+ hasProportionBarChart,
hasSingleSeriesOutput,
hasTrendsFormula,
isTrends,
breakdown,
breakdowns,
+ currentDisplay,
+ isComparing,
}: ChartDisplayOptionEligibility): ChartDisplayOptionGroup[] {
const breakdownProps = breakdownProperties({ breakdown, breakdowns })
const worldMapBreakdownDisabled =
@@ -106,6 +118,11 @@ export function getChartDisplayOptions({
trendsOnlyDisabledReason ||
breakdownDisabledReason ||
(boxPlotMissingProperty ? 'Select a numeric property to use a box plot.' : undefined)
+ // One bar has one total, so a second period's parts would share it.
+ const proportionBarDisabledReason =
+ trendsOnlyDisabledReason ||
+ (isComparing ? "This type doesn't support comparing to a previous period." : undefined) ||
+ (hasProportionBarChart ? undefined : "This type isn't available yet.")
return [
{
@@ -200,6 +217,17 @@ export function getChartDisplayOptions({
description: 'Proportions of a whole as a ring.',
disabledReason: trendsOnlyDisabledReason,
},
+ ...(offersProportionBar(hasProportionBarChart, currentDisplay)
+ ? [
+ {
+ display: ChartDisplayType.ActionsProportionBar,
+ icon: 'proportionBar' as const,
+ label: 'Proportion bar',
+ description: 'Proportions of a whole as one flat bar.',
+ disabledReason: proportionBarDisabledReason,
+ },
+ ]
+ : []),
{
display: ChartDisplayType.ActionsBarValue,
icon: 'horizontalBar',
diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.ts
index c572122fc02c..7ada7fdafe43 100644
--- a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.ts
+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.ts
@@ -174,6 +174,7 @@ const RECIPES: Partial<Record<ChartDisplayType, PreviewRecipe>> = {
[ChartDisplayType.BoldNumber]: { needs: 'totals', when: noBreakdown },
[ChartDisplayType.ActionsPie]: { needs: 'totals' },
[ChartDisplayType.ActionsDonut]: { needs: 'totals' },
+ [ChartDisplayType.ActionsProportionBar]: { needs: 'totals' },
[ChartDisplayType.ActionsBarValue]: { needs: 'totals' },
[ChartDisplayType.ActionsTable]: { needs: 'totals' },
[ChartDisplayType.WorldMap]: { needs: 'totals', when: completeCountries, sampleRows: sampleWorldMapRows },
diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartRecommendations.test.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartRecommendations.test.ts
index 9140d288a452..431a2ecf0315 100644
--- a/products/product_analytics/frontend/insights/chartAlternatives/chartRecommendations.test.ts
+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartRecommendations.test.ts
@@ -22,13 +22,15 @@ function makeTrendsQuery(overrides: Partial<TrendsQuery> = {}): TrendsQuery {
}
}
-const compatibleOptions = getChartDisplayOptions({
- isTrends: true,
- hasSingleSeriesOutput: true,
- hasTrendsFormula: false,
- boxPlotMissingProperty: false,
- hasMetricInsight: true,
-})
+const compatibleOptions = (hasProportionBarChart: boolean): ReturnType<typeof getChartDisplayOptions> =>
+ getChartDisplayOptions({
+ isTrends: true,
+ hasSingleSeriesOutput: true,
+ hasTrendsFormula: false,
+ boxPlotMissingProperty: false,
+ hasMetricInsight: true,
+ hasProportionBarChart,
+ })
describe('getChartAlternatives', () => {
it.each([
@@ -107,6 +109,22 @@ describe('getChartAlternatives', () => {
}),
expected: [ChartDisplayType.ActionsDonut, ChartDisplayType.ActionsBarValue, ChartDisplayType.Metric],
},
+ {
+ name: 'suggests the proportion bar with the other parts-of-a-whole charts when its flag is on',
+ hasProportionBarChart: true,
+ query: makeTrendsQuery({
+ series: [
+ { kind: NodeKind.EventsNode, event: '$pageview', math: BaseMathType.TotalCount },
+ { kind: NodeKind.EventsNode, event: '$autocapture', math: BaseMathType.TotalCount },
+ ],
+ trendsFilter: { display: ChartDisplayType.ActionsPie },
+ }),
+ expected: [
+ ChartDisplayType.ActionsDonut,
+ ChartDisplayType.ActionsProportionBar,
+ ChartDisplayType.ActionsBarValue,
+ ],
+ },
{
name: 'does not suggest proportion charts for a pie chart of one series',
query: makeTrendsQuery({ trendsFilter: { display: ChartDisplayType.ActionsPie } }),
@@ -135,7 +153,9 @@ describe('getChartAlternatives', () => {
ChartDisplayType.ActionsLineGraph,
],
},
- ])('$name', ({ query, expected }) => {
- expect(getChartAlternatives(compatibleOptions, query).map((option) => option.display)).toEqual(expected)
+ ])('$name', ({ query, expected, hasProportionBarChart = false }) => {
+ expect(
+ getChartAlternatives(compatibleOptions(hasProportionBarChart), query).map((option) => option.display)
+ ).toEqual(expected)
})
})
diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartRecommendations.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartRecommendations.ts
index ac886d731b0d..2acd2b79cd98 100644
--- a/products/product_analytics/frontend/insights/chartAlternatives/chartRecommendations.ts
+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartRecommendations.ts
@@ -1,5 +1,5 @@
import { convertPropertyGroupToProperties } from 'lib/components/PropertyFilters/utils'
-import { DISPLAY_TYPES_TO_CATEGORIES, NON_BREAKDOWN_DISPLAY_TYPES, PIE_DISPLAY_TYPES } from 'lib/constants'
+import { DISPLAY_TYPES_TO_CATEGORIES, NON_BREAKDOWN_DISPLAY_TYPES, PART_OF_WHOLE_DISPLAY_TYPES } from 'lib/constants'
import { isPropertyValueMath } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/mathUtils'
import type { BreakdownFilter, TrendsQuery } from '~/queries/schema/schema-general'
@@ -88,7 +88,7 @@ function rankRecommendations(query: TrendsQuery | null, currentDisplay: ChartDis
DISPLAY_TYPES_TO_CATEGORIES[currentDisplay] === ChartDisplayCategory.TotalValue &&
hasMultipleParts(query)
) {
- boosted.push(...PIE_DISPLAY_TYPES, ChartDisplayType.ActionsBarValue)
+ boosted.push(...PART_OF_WHOLE_DISPLAY_TYPES, ChartDisplayType.ActionsBarValue)
}
}
const ranked = [...new Set([...boosted, ...DEFAULT_RECOMMENDATION_ORDER])]
diff --git a/products/product_analytics/frontend/insights/trends/Trends.tsx b/products/product_analytics/frontend/insights/trends/Trends.tsx
index 5f9b34da535e..9061fec047b2 100644
--- a/products/product_analytics/frontend/insights/trends/Trends.tsx
+++ b/products/product_analytics/frontend/insights/trends/Trends.tsx
@@ -23,6 +23,7 @@ import { TrendsBarChart } from 'products/product_analytics/frontend/insights/tre
import { TrendsLifecycleChart } from 'products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart'
import { TrendsLineChart } from 'products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart'
import { TrendsPieChart } from 'products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart'
+import { TrendsProportionBar } from 'products/product_analytics/frontend/insights/trends/TrendsProportionBar/TrendsProportionBar'
import { TrendsSlopeChart } from 'products/product_analytics/frontend/insights/trends/TrendsSlopeChart/TrendsSlopeChart'
import { trendsDataLogic } from './trendsDataLogic'
@@ -89,6 +90,15 @@ export function TrendInsight({ view, context, embedded, inSharedMode, editMode }
if (display && PIE_DISPLAY_TYPES.includes(display)) {
return <TrendsPieChart context={context} inSharedMode={inSharedMode} showPersonsModal={showPersonsModal} />
}
+ if (display === ChartDisplayType.ActionsProportionBar) {
+ return (
+ <TrendsProportionBar
+ context={context}
+ inSharedMode={inSharedMode}
+ showPersonsModal={showPersonsModal}
+ />
+ )
+ }
if (display === ChartDisplayType.ActionsBarValue) {
return <TrendsBarChart context={context} inSharedMode={inSharedMode} embedded={embedded} />
}
diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.test.tsx
index 179f28ac641c..2cd5352b7aed 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.test.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.test.tsx
@@ -39,7 +39,7 @@ const pieByHedgehog = (trendsFilter: Record<string, unknown> = {}): ReturnType<t
trendsFilter: { display: ChartDisplayType.ActionsPie, showValuesOnSeries: true, ...trendsFilter },
})
-describe('TrendsPieChart (ActionsPie)', () => {
+describe('TrendsPieChart', () => {
it.each([
{
name: 'shows raw slice values when percent stack view is off',
@@ -75,6 +75,21 @@ describe('TrendsPieChart (ActionsPie)', () => {
expect([...sliceLabels()].sort()).toEqual([...expectedLabels].sort())
})
+ it('floors a negative part at 0 in the total, matching the slices the pie draws', async () => {
+ const { container } = renderInsight({
+ query: buildTrendsQuery({
+ series: [
+ { kind: NodeKind.EventsNode, event: 'NappedWithNegativePart', name: 'NappedWithNegativePart' },
+ ],
+ breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },
+ trendsFilter: { display: ChartDisplayType.ActionsPie },
+ }),
+ })
+ await screen.findByLabelText(/pie chart with/i, undefined, { timeout: 5000 })
+
+ expect(container.querySelector('[data-attr="trend-total"]')).toHaveTextContent('10')
+ })
+
describe('quill in-chart legend', () => {
const getInChartLegend = (container: HTMLElement): HTMLElement | null =>
container.querySelector<HTMLElement>('[data-attr="hog-chart-pie-legend"]')
diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx
index cb533c34bf06..ad872fddb471 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx
@@ -1,46 +1,21 @@
import clsx from 'clsx'
import { useValues } from 'kea'
import posthog from 'posthog-js'
-import { useCallback, useMemo, type ErrorInfo } from 'react'
+import { useMemo, type ErrorInfo } from 'react'
import { PieChart } from '@posthog/quill-charts'
-import type { PieChartConfig, RadialSlicePayload, Series, TooltipContext } from '@posthog/quill-charts'
+import type { PieChartConfig } from '@posthog/quill-charts'
-import { useChartTheme } from 'lib/charts/hooks'
-import {
- formatAggregationAxisValue,
- formatAggregationAxisValueWithShareOfTotal,
-} from 'scenes/insights/aggregationAxisFormat'
import { InsightEmptyState } from 'scenes/insights/EmptyStates'
import { insightLogic } from 'scenes/insights/insightLogic'
-import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'
-import { teamLogic } from 'scenes/teamLogic'
-import { openPersonsModal } from 'scenes/trends/persons-modal/PersonsModal'
-import { cohortsModel } from '~/models/cohortsModel'
-import { groupsModel } from '~/models/groupsModel'
-import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
-import { InsightVizNode } from '~/queries/schema/schema-general'
-import { QueryContext } from '~/queries/types'
import { ChartDisplayType } from '~/types'
import { trendsDataLogic } from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'
-import type { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'
-import { datasetToActorsQuery } from 'products/product_analytics/frontend/insights/trends/viz/datasetToActorsQuery'
-import { InsightSeriesTooltip } from '../../shared/InsightSeriesTooltip'
-import { getSeriesIdentification } from '../../shared/seriesIdentification'
-import { getTrendsSeriesDisplayLabel } from '../shared/getTrendsSeriesDisplayLabel'
-import { buildTrendsSeriesMeta, type TrendsSeriesMeta } from '../shared/trendsSeriesMeta'
-import { useInsightsLegendConfig } from '../shared/useInsightsLegendConfig'
+import type { TrendsSeriesMeta } from '../shared/trendsSeriesMeta'
+import { type TrendsPartOfWholeChartProps, useTrendsPartOfWholeChart } from '../shared/useTrendsPartOfWholeChart'
import { DonutCenterLabel } from './DonutCenterLabel'
-import { buildTrendsPieSeries } from './trendsPieTransforms'
-
-interface TrendsPieChartProps {
- context?: QueryContext<InsightVizNode>
- inSharedMode?: boolean
- showPersonsModal?: boolean
-}
const DONUT_INNER_RADIUS_RATIO = 0.6
@@ -51,104 +26,33 @@ const handleChartError = (error: Error, info: ErrorInfo): void => {
})
}
-export function TrendsPieChart({
- context,
- inSharedMode,
- showPersonsModal = true,
-}: TrendsPieChartProps): JSX.Element | null {
- const theme = useChartTheme()
+export function TrendsPieChart(props: TrendsPartOfWholeChartProps): JSX.Element | null {
+ const { context } = props
+ const {
+ theme,
+ legendConfig,
+ series,
+ hasResults,
+ showAggregation,
+ formattedTotal,
+ valueFormatter,
+ renderTooltip,
+ onSliceClick,
+ } = useTrendsPartOfWholeChart(props)
const { insightProps } = useValues(insightLogic)
- const legendConfig = useInsightsLegendConfig({ insightProps, inSharedMode })
- const { baseCurrency } = useValues(teamLogic)
- const { allCohorts } = useValues(cohortsModel)
- const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)
- const { aggregationLabel } = useValues(groupsModel)
-
const {
display,
- indexedResults,
- trendsFilter,
- formula,
showValuesOnSeries,
showLabelOnSeries,
showPercentStackView,
supportsPercentStackView,
pieChartVizOptions,
- hasDataWarehouseSeries,
- querySource,
- breakdownFilter,
- labelGroupType,
- getTrendsColor,
- getTrendsHidden,
- isSingleSeriesDefinition,
} = useValues(trendsDataLogic(insightProps))
const isPercentStackView = !!showPercentStackView && !!supportsPercentStackView
- const seriesIdentification = useMemo(
- () => getSeriesIdentification((indexedResults ?? []).map(buildTrendsSeriesMeta)),
- [indexedResults]
- )
-
- const resolvedGroupTypeLabel =
- context?.groupTypeLabel ??
- (labelGroupType === 'people'
- ? 'people'
- : labelGroupType === 'none'
- ? ''
- : aggregationLabel(labelGroupType).plural)
-
- const onDataPointClick = context?.onDataPointClick
- const showAggregation = !pieChartVizOptions?.hideAggregation
const isDonut = display === ChartDisplayType.ActionsDonut
- // 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 =>
- getTrendsSeriesDisplayLabel(r, {
- breakdownFilter,
- cohorts: allCohorts.results,
- formatPropertyValueForDisplay,
- isSingleSeriesDefinition,
- seriesIdentification,
- }),
- [
- breakdownFilter,
- allCohorts.results,
- formatPropertyValueForDisplay,
- isSingleSeriesDefinition,
- seriesIdentification,
- ]
- )
-
- const series: Series<TrendsSeriesMeta>[] = useMemo(
- () =>
- buildTrendsPieSeries(indexedResults ?? [], {
- getColor: getTrendsColor,
- // 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, getLabel]
- )
-
- const visibleResults = useMemo(
- () => ((indexedResults ?? []) as IndexedTrendResult[]).filter((r) => !getTrendsHidden(r)),
- [indexedResults, getTrendsHidden]
- )
-
- const total = useMemo(
- () => visibleResults.reduce((acc: number, r: IndexedTrendResult) => acc + (r.aggregated_value ?? 0), 0),
- [visibleResults]
- )
-
- const valueFormatter = useCallback(
- (v: number) => formatAggregationAxisValue(trendsFilter, v, baseCurrency),
- [trendsFilter, baseCurrency]
- )
-
// Values and percentages are independent on a pie: either one alone puts that number on the
// slice, and both together read as `352 (18.4%)`, matching the tooltip.
const showValue = !!showValuesOnSeries
@@ -175,105 +79,9 @@ export function TrendsPieChart({
]
)
- // ActionsPie disables clicks entirely when the insight has data-warehouse series (see
- // ActionsPie.tsx — `onClick={hasDataWarehouseSeries ? undefined : onClick}`); match that here.
- const canHandleClick = !hasDataWarehouseSeries && (!!onDataPointClick || (showPersonsModal && !formula))
-
- // Click parity with ActionsPie. The legacy path builds an InsightActorsQuery from the
- // GraphDataset.breakdownValues array; here each slice is already a single result, so we
- // pull its breakdown/compare straight from the IndexedTrendResult.
- const handleSliceClick = useCallback(
- (seriesKey: string, label: string | undefined) => {
- const result = visibleResults.find((r: IndexedTrendResult) => String(r.id) === seriesKey)
- if (!result) {
- return
- }
- if (onDataPointClick) {
- onDataPointClick(
- {
- breakdown: result.breakdown_value,
- compare: result.compare_label || undefined,
- },
- // Legacy parity with ActionsPie — passes the first result, not the clicked one.
- (indexedResults ?? [])[0]
- )
- return
- }
- if (!showPersonsModal || formula || hasDataWarehouseSeries || !querySource) {
- return
- }
- openPersonsModal({
- title: label || '',
- query: datasetToActorsQuery({
- dataset: {
- action: result.action,
- breakdown_value: result.breakdown_value,
- compare_label: result.compare_label,
- },
- query: querySource,
- }),
- additionalSelect: {
- value_at_data_point: 'event_count',
- matched_recordings: 'matched_recordings',
- },
- orderBy: ['event_count DESC, actor_id DESC'],
- })
- },
- [
- visibleResults,
- indexedResults,
- onDataPointClick,
- showPersonsModal,
- formula,
- hasDataWarehouseSeries,
- querySource,
- ]
- )
-
- const onSliceClick = useCallback(
- (payload: RadialSlicePayload<TrendsSeriesMeta>) => handleSliceClick(payload.series.key, payload.series.label),
- [handleSliceClick]
- )
-
- const renderCount = useCallback(
- (value: number) => formatAggregationAxisValueWithShareOfTotal(trendsFilter, value, total, baseCurrency),
- [trendsFilter, total, baseCurrency]
- )
-
- const onRowClick = useMemo(
- () => (canHandleClick ? (datum: SeriesDatum) => handleSliceClick(String(datum.id), datum.label) : undefined),
- [canHandleClick, handleSliceClick]
- )
-
- const renderTooltip = useCallback(
- (ctx: TooltipContext<TrendsSeriesMeta>) => {
- const sharedProps = {
- context: ctx,
- breakdownFilter: breakdownFilter ?? undefined,
- trendsFilter,
- baseCurrency,
- groupTypeLabel: resolvedGroupTypeLabel,
- formatCompareLabel: context?.formatCompareLabel,
- onRowClick,
- showHeader: false as const,
- renderCount,
- }
- return <InsightSeriesTooltip {...sharedProps} />
- },
- [
- breakdownFilter,
- trendsFilter,
- baseCurrency,
- resolvedGroupTypeLabel,
- context?.formatCompareLabel,
- onRowClick,
- renderCount,
- ]
- )
-
// 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) {
+ if (!hasResults) {
return (
<InsightEmptyState
heading={context?.emptyStateHeading}
@@ -291,10 +99,7 @@ export function TrendsPieChart({
// A donut's hollow center is the natural home for the total, so move it there instead of
// stranding it below the chart.
- const centerLabel =
- isDonut && showAggregation ? (
- <DonutCenterLabel>{formatAggregationAxisValue(trendsFilter, total, baseCurrency)}</DonutCenterLabel>
- ) : undefined
+ const centerLabel = isDonut && showAggregation ? <DonutCenterLabel>{formattedTotal}</DonutCenterLabel> : undefined
const pie = (
<PieChart<TrendsSeriesMeta>
@@ -302,7 +107,7 @@ export function TrendsPieChart({
theme={theme}
config={pieConfig}
tooltip={renderTooltip}
- onSliceClick={canHandleClick ? onSliceClick : undefined}
+ onSliceClick={onSliceClick}
valueFormatter={valueFormatter}
centerLabel={centerLabel}
dataAttr="trend-pie-graph"
@@ -317,8 +122,11 @@ export function TrendsPieChart({
<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 && !isDonut && (
- <div className={clsx('text-7xl text-center font-bold m-0', legendAtBottom && 'mt-6')}>
- {formatAggregationAxisValue(trendsFilter, total, baseCurrency)}
+ <div
+ className={clsx('text-7xl text-center font-bold m-0', legendAtBottom && 'mt-6')}
+ data-attr="trend-total"
+ >
+ {formattedTotal}
</div>
)}
</div>
diff --git a/products/product_analytics/frontend/insights/trends/TrendsProportionBar/TrendsProportionBar.stories.tsx b/products/product_analytics/frontend/insights/trends/TrendsProportionBar/TrendsProportionBar.stories.tsx
new file mode 100644
index 000000000000..89cd10bc51d0
--- /dev/null
+++ b/products/product_analytics/frontend/insights/trends/TrendsProportionBar/TrendsProportionBar.stories.tsx
@@ -0,0 +1,81 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { BindLogic } from 'kea'
+import { useState } from 'react'
+
+import { insightLogic } from 'scenes/insights/insightLogic'
+
+import { mswDecorator } from '~/mocks/browser'
+import trendsPieBreakdownFixture from '~/mocks/fixtures/api/projects/team_id/insights/trendsPieBreakdown.json'
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import type { DataNodeLogicProps } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/InsightViz'
+import { getCachedResults } from '~/queries/nodes/InsightViz/utils'
+import { ChartDisplayType, type InsightLogicProps, type InsightShortId } from '~/types'
+
+import { TrendsProportionBar } from './TrendsProportionBar'
+
+type Story = StoryObj<{}>
+
+const meta: Meta = {
+ title: 'Insights/TrendsProportionBar',
+ component: TrendsProportionBar,
+ parameters: {
+ layout: 'centered',
+ mockDate: '2023-07-11',
+ testOptions: { snapshotBrowsers: ['chromium'] },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/annotations/': {
+ count: 0,
+ next: null,
+ previous: null,
+ results: [],
+ },
+ },
+ }),
+ ],
+}
+export default meta
+
+let uniqueNode = 0
+
+function BreakdownProportionBar(): JSX.Element {
+ const [dashboardItemId] = useState(() => `TrendsProportionBarStory.${uniqueNode++}` as InsightShortId)
+ const source = trendsPieBreakdownFixture.query.source
+ const cachedInsight: any = {
+ ...trendsPieBreakdownFixture,
+ short_id: dashboardItemId,
+ query: {
+ ...trendsPieBreakdownFixture.query,
+ source: {
+ ...source,
+ trendsFilter: { ...source.trendsFilter, display: ChartDisplayType.ActionsProportionBar },
+ },
+ },
+ }
+
+ const insightProps: InsightLogicProps = { dashboardItemId, doNotLoad: true, cachedInsight }
+ const dataNodeLogicProps: DataNodeLogicProps = {
+ query: cachedInsight.query.source,
+ key: insightVizDataNodeKey(insightProps),
+ cachedResults: getCachedResults(cachedInsight, cachedInsight.query.source),
+ doNotLoad: true,
+ }
+
+ return (
+ <BindLogic logic={insightLogic} props={insightProps}>
+ <BindLogic logic={dataNodeLogic} props={dataNodeLogicProps}>
+ {/* eslint-disable-next-line react/forbid-dom-props */}
+ <div style={{ height: 360, width: 720, display: 'flex', flexDirection: 'column' }}>
+ <TrendsProportionBar />
+ </div>
+ </BindLogic>
+ </BindLogic>
+ )
+}
+
+export const Breakdown: Story = {
+ render: () => <BreakdownProportionBar />,
+}
diff --git a/products/product_analytics/frontend/insights/trends/TrendsProportionBar/TrendsProportionBar.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsProportionBar/TrendsProportionBar.test.tsx
new file mode 100644
index 000000000000..ca078a85fb12
--- /dev/null
+++ b/products/product_analytics/frontend/insights/trends/TrendsProportionBar/TrendsProportionBar.test.tsx
@@ -0,0 +1,96 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, waitFor } from '@testing-library/react'
+
+import { getHogChart, setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'
+
+import { NodeKind } from '~/queries/schema/schema-general'
+import { buildTrendsQuery, renderInsight } from '~/test/insight-testing'
+import { ChartDisplayType } from '~/types'
+
+let cleanupJsdom: () => void
+let cleanupRaf: () => void
+
+beforeEach(() => {
+ cleanupJsdom = setupJsdom()
+ cleanupRaf = setupSyncRaf()
+})
+
+afterEach(() => {
+ cleanupRaf()
+ cleanupJsdom()
+ cleanup()
+})
+
+describe('TrendsProportionBar', () => {
+ it.each([
+ {
+ name: 'shows the legend with each share by default, because the bar has no axis',
+ showLegend: undefined,
+ expectedRows: [
+ { label: 'Spike', secondaryLabel: '57.9% · 11' },
+ { label: 'Thistle', secondaryLabel: '21.1% · 4' },
+ { label: 'Bramble', secondaryLabel: '10.5% · 2' },
+ { label: 'Prickles', secondaryLabel: '10.5% · 2' },
+ { label: 'Conker', secondaryLabel: '0% · 0' },
+ ],
+ },
+ { name: 'hides the legend when the user turns it off', showLegend: false, expectedRows: [] },
+ {
+ name: 'starts with the legend off when there are many parts',
+ event: 'NappedByManyHedgehogs',
+ showLegend: undefined,
+ expectedRows: [],
+ },
+ ])('$name', async ({ event = 'Napped', showLegend, expectedRows }) => {
+ const { container } = renderInsight({
+ query: buildTrendsQuery({
+ series: [{ kind: NodeKind.EventsNode, event, name: event }],
+ breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },
+ trendsFilter: { display: ChartDisplayType.ActionsProportionBar, showLegend },
+ }),
+ })
+ await waitFor(() => expect(container.querySelector('[data-attr="trend-proportion-bar"]')).not.toBeNull(), {
+ timeout: 5000,
+ })
+
+ expect(getHogChart(container).legendItems()).toEqual(expectedRows)
+ })
+
+ it('floors a negative part at 0 in the total below the bar, matching what the bar renders', async () => {
+ const { container } = renderInsight({
+ query: buildTrendsQuery({
+ series: [
+ {
+ kind: NodeKind.EventsNode,
+ event: 'NappedWithNegativePart',
+ name: 'NappedWithNegativePart',
+ },
+ ],
+ breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },
+ trendsFilter: { display: ChartDisplayType.ActionsProportionBar },
+ }),
+ })
+ await waitFor(() => expect(container.querySelector('[data-attr="trend-proportion-bar"]')).not.toBeNull(), {
+ timeout: 5000,
+ })
+
+ // The bar floors -4 at 0, so the total reads 10, not the raw sum of 6.
+ expect(container.querySelector('[data-attr="trend-total"]')).toHaveTextContent('10')
+ })
+
+ it('leaves the previous period out of a bar saved with compare on', async () => {
+ const { container } = renderInsight({
+ query: buildTrendsQuery({
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' }],
+ trendsFilter: { display: ChartDisplayType.ActionsProportionBar },
+ compareFilter: { compare: true },
+ }),
+ })
+ await waitFor(() => expect(container.querySelector('[data-attr="trend-proportion-bar"]')).not.toBeNull(), {
+ timeout: 5000,
+ })
+
+ expect(getHogChart(container).legendItems()).toHaveLength(1)
+ })
+})
diff --git a/products/product_analytics/frontend/insights/trends/TrendsProportionBar/TrendsProportionBar.tsx b/products/product_analytics/frontend/insights/trends/TrendsProportionBar/TrendsProportionBar.tsx
new file mode 100644
index 000000000000..66d457d002ae
--- /dev/null
+++ b/products/product_analytics/frontend/insights/trends/TrendsProportionBar/TrendsProportionBar.tsx
@@ -0,0 +1,58 @@
+import { ProportionBar } from '@posthog/quill-charts'
+import type { ProportionBarConfig } from '@posthog/quill-charts'
+
+import { useChartConfig } from 'lib/charts/hooks'
+import { InsightEmptyState } from 'scenes/insights/EmptyStates'
+
+import { makeChartErrorHandler } from '../shared/chartErrorHandler'
+import type { TrendsSeriesMeta } from '../shared/trendsSeriesMeta'
+import { type TrendsPartOfWholeChartProps, useTrendsPartOfWholeChart } from '../shared/useTrendsPartOfWholeChart'
+
+const handleChartError = makeChartErrorHandler('trends-proportion-bar')
+
+export function TrendsProportionBar(props: TrendsPartOfWholeChartProps): JSX.Element {
+ const { context } = props
+ const {
+ theme,
+ legendConfig,
+ series,
+ hasResults,
+ showAggregation,
+ formattedTotal,
+ valueFormatter,
+ renderTooltip,
+ onSliceClick,
+ } = useTrendsPartOfWholeChart(props)
+
+ const config: ProportionBarConfig = useChartConfig(() => ({ legend: legendConfig }), [legendConfig])
+
+ if (!hasResults) {
+ return (
+ <InsightEmptyState
+ heading={context?.emptyStateHeading}
+ detail={context?.emptyStateDetail}
+ sampleDataVariant="proportionBar"
+ />
+ )
+ }
+
+ return (
+ <div className="flex flex-col w-full flex-1 min-h-0 justify-center gap-6">
+ <ProportionBar<TrendsSeriesMeta>
+ series={series}
+ theme={theme}
+ config={config}
+ tooltip={renderTooltip}
+ onSliceClick={onSliceClick}
+ valueFormatter={valueFormatter}
+ dataAttr="trend-proportion-bar"
+ onError={handleChartError}
+ />
+ {showAggregation && (
+ <div className="text-7xl text-center font-bold m-0" data-attr="trend-total">
+ {formattedTotal}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/trends/shared/useTrendsPartOfWholeChart.tsx b/products/product_analytics/frontend/insights/trends/shared/useTrendsPartOfWholeChart.tsx
new file mode 100644
index 000000000000..04051633800a
--- /dev/null
+++ b/products/product_analytics/frontend/insights/trends/shared/useTrendsPartOfWholeChart.tsx
@@ -0,0 +1,253 @@
+import { useValues } from 'kea'
+import { useCallback, useMemo } from 'react'
+
+import type { ChartLegendConfig, ChartTheme, RadialSlicePayload, Series, TooltipContext } from '@posthog/quill-charts'
+
+import { useChartTheme } from 'lib/charts/hooks'
+import {
+ formatAggregationAxisValue,
+ formatAggregationAxisValueWithShareOfTotal,
+} from 'scenes/insights/aggregationAxisFormat'
+import { insightLogic } from 'scenes/insights/insightLogic'
+import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'
+import { teamLogic } from 'scenes/teamLogic'
+import { openPersonsModal } from 'scenes/trends/persons-modal/PersonsModal'
+
+import { cohortsModel } from '~/models/cohortsModel'
+import { groupsModel } from '~/models/groupsModel'
+import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
+import { InsightVizNode } from '~/queries/schema/schema-general'
+import { QueryContext } from '~/queries/types'
+
+import { trendsDataLogic } from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'
+import type { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'
+import { datasetToActorsQuery } from 'products/product_analytics/frontend/insights/trends/viz/datasetToActorsQuery'
+
+import { InsightSeriesTooltip } from '../../shared/InsightSeriesTooltip'
+import { getSeriesIdentification } from '../../shared/seriesIdentification'
+import { buildTrendsPieSeries } from '../TrendsPieChart/trendsPieTransforms'
+import { getTrendsSeriesDisplayLabel } from './getTrendsSeriesDisplayLabel'
+import { buildTrendsSeriesMeta, type TrendsSeriesMeta } from './trendsSeriesMeta'
+import { useInsightsLegendConfig } from './useInsightsLegendConfig'
+
+export interface TrendsPartOfWholeChartProps {
+ context?: QueryContext<InsightVizNode>
+ inSharedMode?: boolean
+ showPersonsModal?: boolean
+}
+
+export interface TrendsPartOfWholeChart {
+ theme: ChartTheme
+ legendConfig: ChartLegendConfig
+ series: Series<TrendsSeriesMeta>[]
+ hasResults: boolean
+ showAggregation: boolean
+ formattedTotal: string
+ valueFormatter: (value: number) => string
+ renderTooltip: (ctx: TooltipContext<TrendsSeriesMeta>) => JSX.Element
+ onSliceClick: ((payload: RadialSlicePayload<TrendsSeriesMeta>) => void) | undefined
+}
+
+/** The data, legend, total, tooltip and click handling a trends pie, donut or proportion bar shares. */
+export function useTrendsPartOfWholeChart({
+ context,
+ inSharedMode,
+ showPersonsModal = true,
+}: TrendsPartOfWholeChartProps): TrendsPartOfWholeChart {
+ const theme = useChartTheme()
+
+ const { insightProps } = useValues(insightLogic)
+ const legendConfig = useInsightsLegendConfig({ insightProps, inSharedMode })
+ const { baseCurrency } = useValues(teamLogic)
+ const { allCohorts } = useValues(cohortsModel)
+ const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)
+ const { aggregationLabel } = useValues(groupsModel)
+
+ const {
+ indexedResults,
+ trendsFilter,
+ formula,
+ pieChartVizOptions,
+ hasDataWarehouseSeries,
+ querySource,
+ breakdownFilter,
+ labelGroupType,
+ getTrendsColor,
+ getTrendsHidden,
+ isSingleSeriesDefinition,
+ } = useValues(trendsDataLogic(insightProps))
+
+ const seriesIdentification = useMemo(
+ () => getSeriesIdentification((indexedResults ?? []).map(buildTrendsSeriesMeta)),
+ [indexedResults]
+ )
+
+ const resolvedGroupTypeLabel =
+ context?.groupTypeLabel ??
+ (labelGroupType === 'people'
+ ? 'people'
+ : labelGroupType === 'none'
+ ? ''
+ : aggregationLabel(labelGroupType).plural)
+
+ const onDataPointClick = context?.onDataPointClick
+
+ // 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 =>
+ getTrendsSeriesDisplayLabel(r, {
+ breakdownFilter,
+ cohorts: allCohorts.results,
+ formatPropertyValueForDisplay,
+ isSingleSeriesDefinition,
+ seriesIdentification,
+ }),
+ [
+ breakdownFilter,
+ allCohorts.results,
+ formatPropertyValueForDisplay,
+ isSingleSeriesDefinition,
+ seriesIdentification,
+ ]
+ )
+
+ const series: Series<TrendsSeriesMeta>[] = useMemo(
+ () =>
+ buildTrendsPieSeries(indexedResults ?? [], {
+ getColor: getTrendsColor,
+ // 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, getLabel]
+ )
+
+ const visibleResults = useMemo(
+ () => ((indexedResults ?? []) as IndexedTrendResult[]).filter((r) => !getTrendsHidden(r)),
+ [indexedResults, getTrendsHidden]
+ )
+
+ const total = useMemo(
+ () =>
+ // Floored like the charts floor a part, so the total matches what they draw.
+ visibleResults.reduce((acc: number, r: IndexedTrendResult) => {
+ const value = r.aggregated_value ?? 0
+ return acc + (Number.isFinite(value) ? Math.max(0, value) : 0)
+ }, 0),
+ [visibleResults]
+ )
+
+ const valueFormatter = useCallback(
+ (v: number) => formatAggregationAxisValue(trendsFilter, v, baseCurrency),
+ [trendsFilter, baseCurrency]
+ )
+
+ // ActionsPie disables clicks entirely when the insight has data-warehouse series (see
+ // ActionsPie.tsx — `onClick={hasDataWarehouseSeries ? undefined : onClick}`); match that here.
+ const canHandleClick = !hasDataWarehouseSeries && (!!onDataPointClick || (showPersonsModal && !formula))
+
+ // Click parity with ActionsPie. The legacy path builds an InsightActorsQuery from the
+ // GraphDataset.breakdownValues array; here each slice is already a single result, so we
+ // pull its breakdown/compare straight from the IndexedTrendResult.
+ const handleSliceClick = useCallback(
+ (seriesKey: string, label: string | undefined) => {
+ const result = visibleResults.find((r: IndexedTrendResult) => String(r.id) === seriesKey)
+ if (!result) {
+ return
+ }
+ if (onDataPointClick) {
+ onDataPointClick(
+ {
+ breakdown: result.breakdown_value,
+ compare: result.compare_label || undefined,
+ },
+ // Legacy parity with ActionsPie — passes the first result, not the clicked one.
+ (indexedResults ?? [])[0]
+ )
+ return
+ }
+ if (!showPersonsModal || formula || hasDataWarehouseSeries || !querySource) {
+ return
+ }
+ openPersonsModal({
+ title: label || '',
+ query: datasetToActorsQuery({
+ dataset: {
+ action: result.action,
+ breakdown_value: result.breakdown_value,
+ compare_label: result.compare_label,
+ },
+ query: querySource,
+ }),
+ additionalSelect: {
+ value_at_data_point: 'event_count',
+ matched_recordings: 'matched_recordings',
+ },
+ orderBy: ['event_count DESC, actor_id DESC'],
+ })
+ },
+ [
+ visibleResults,
+ indexedResults,
+ onDataPointClick,
+ showPersonsModal,
+ formula,
+ hasDataWarehouseSeries,
+ querySource,
+ ]
+ )
+
+ const onSliceClick = useCallback(
+ (payload: RadialSlicePayload<TrendsSeriesMeta>) => handleSliceClick(payload.series.key, payload.series.label),
+ [handleSliceClick]
+ )
+
+ const renderCount = useCallback(
+ (value: number) => formatAggregationAxisValueWithShareOfTotal(trendsFilter, value, total, baseCurrency),
+ [trendsFilter, total, baseCurrency]
+ )
+
+ const onRowClick = useMemo(
+ () => (canHandleClick ? (datum: SeriesDatum) => handleSliceClick(String(datum.id), datum.label) : undefined),
+ [canHandleClick, handleSliceClick]
+ )
+
+ const renderTooltip = useCallback(
+ (ctx: TooltipContext<TrendsSeriesMeta>) => (
+ <InsightSeriesTooltip
+ context={ctx}
+ breakdownFilter={breakdownFilter ?? undefined}
+ trendsFilter={trendsFilter}
+ baseCurrency={baseCurrency}
+ groupTypeLabel={resolvedGroupTypeLabel}
+ formatCompareLabel={context?.formatCompareLabel}
+ onRowClick={onRowClick}
+ showHeader={false}
+ renderCount={renderCount}
+ />
+ ),
+ [
+ breakdownFilter,
+ trendsFilter,
+ baseCurrency,
+ resolvedGroupTypeLabel,
+ context?.formatCompareLabel,
+ onRowClick,
+ renderCount,
+ ]
+ )
+
+ return {
+ theme,
+ legendConfig,
+ series,
+ hasResults: !!(indexedResults ?? []).length,
+ showAggregation: !pieChartVizOptions?.hideAggregation,
+ formattedTotal: formatAggregationAxisValue(trendsFilter, total, baseCurrency),
+ valueFormatter,
+ renderTooltip,
+ onSliceClick: canHandleClick ? onSliceClick : undefined,
+ }
+}
diff --git a/products/product_analytics/frontend/insights/trends/trendsDataLogic.test.ts b/products/product_analytics/frontend/insights/trends/trendsDataLogic.test.ts
index f4cd90c4b12d..4751452b12ab 100644
--- a/products/product_analytics/frontend/insights/trends/trendsDataLogic.test.ts
+++ b/products/product_analytics/frontend/insights/trends/trendsDataLogic.test.ts
@@ -106,6 +106,28 @@ describe('trendsDataLogic', () => {
})
})
+ it('leaves the previous period out of a proportion bar saved with compare on', async () => {
+ const query: TrendsQuery = {
+ kind: NodeKind.TrendsQuery,
+ series: [],
+ trendsFilter: { display: ChartDisplayType.ActionsProportionBar },
+ compareFilter: { compare: true },
+ }
+ const insight: Partial<InsightModel> = {
+ result: [
+ { ...trendResult.result[0], compare: true, compare_label: 'current' },
+ { ...trendResult.result[0], compare: true, compare_label: 'previous' },
+ ],
+ }
+
+ await expectLogic(logic, () => {
+ insightVizDataLogic.findMounted(insightProps)?.actions.updateQuerySource(query)
+ builtDataNodeLogic.actions.loadDataSuccess(insight)
+ }).toMatchValues({
+ indexedResults: [expect.objectContaining({ compare_label: 'current' })],
+ })
+ })
+
it('for pie visualization', async () => {
const query: TrendsQuery = {
kind: NodeKind.TrendsQuery,
diff --git a/products/product_analytics/frontend/insights/trends/trendsDataLogic.ts b/products/product_analytics/frontend/insights/trends/trendsDataLogic.ts
index 87fdc8ebe31e..6e396fc4bea9 100644
--- a/products/product_analytics/frontend/insights/trends/trendsDataLogic.ts
+++ b/products/product_analytics/frontend/insights/trends/trendsDataLogic.ts
@@ -2,7 +2,7 @@ import { MakeLogicType, actions, connect, kea, key, listeners, path, props, redu
import { DataColorTheme, DataColorToken } from 'lib/colors'
import type { Intervals } from 'lib/components/IntervalFilter/intervals'
-import { PIE_DISPLAY_TYPES } from 'lib/constants'
+import { PART_OF_WHOLE_DISPLAY_TYPES } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { isMultiSeriesFormula } from 'lib/utils/strings'
import {
@@ -596,6 +596,11 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
const defaultLifecyclesOrder = ['new', 'resurrecting', 'returning', 'dormant']
let indexedResults = results.map((result, index) => ({ ...result, seriesIndex: index }))
+ // One bar has one total, so a previous period saved with compare on is left out.
+ if (display === ChartDisplayType.ActionsProportionBar) {
+ indexedResults = indexedResults.filter((r) => r.compare_label !== 'previous')
+ }
+
// want the previous bars to show before current bars
if (display === ChartDisplayType.ActionsUnstackedBar && indexedResults.some((x) => x.compare)) {
indexedResults.sort((a, b) => {
@@ -612,7 +617,7 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
})
} else if (
display &&
- (display === ChartDisplayType.ActionsBarValue || PIE_DISPLAY_TYPES.includes(display))
+ (display === ChartDisplayType.ActionsBarValue || PART_OF_WHOLE_DISPLAY_TYPES.includes(display))
) {
indexedResults.sort((a, b) => {
const aValue =