:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(insights): show as % of total on hog-charts pie charts (#61526)
Sam Penningtonea3f9c174bd7
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5c431bb0ec8d..7863a02a7011 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -653,33 +653,33 @@ snapshots:components-hogcharts-metric--number-only--light:hash: v1.k794b7964.9e1fbd475ba802686d23440d747df99abc015757e7708d037f246464fd46a3f8.K1CGuG2R-VxLBu6HLU-jBXWJKH_49rGnbAUx1YnrTcQcomponents-hogcharts-piechart--donut--dark:- hash: v1.k794b7964.53683ceb5ed88f7d3542094db1fb764fc6a2f8908036b3748ac4504695032427.qQAVMSvoraiafCrTL62wowzgaXHrdULwrGIb8d2VwBk+ hash: v1.k794b7964.95f52c48e6476dd49327e572e78275692bf3085a46c78b57d7ccb0f2af33229d.UKy0xtoAM3JGpdygHr-mG_fCI8HoINH0cq0e-w5MuYYcomponents-hogcharts-piechart--donut--light:- hash: v1.k794b7964.acf56c27510ab47148eb147dac441df1fb203c73461fae7d38aed39c9883759b.aGBuBjyBEhAJPjrrC_BepNi2g5zmX73vd2WhSO-tjj0+ hash: v1.k794b7964.0094d02615d384b5473614f1e66499dfc907fe2875f5c643ce4c5612daba4915.zgE_VTPCiOQ9B1ml1I4G1oIxWriQKHrQ00KAqen7Digcomponents-hogcharts-piechart--long-label-tooltip--dark:- hash: v1.k794b7964.d3bcb578618ec73e343c11fc05ccdad95e303c3973e1af922b0bbfd6e36b5dac.5sDDWcQqlACUZke1N8tCP6-3iPy-NvAREIJwMNDWAgY+ hash: v1.k794b7964.2eb01876c36f7266b5ef594afdb4aa059aaeea48c8ad23fd4a99a4ee531ad2bb.KCI5Xfrd-yW-jq4JXylwkbJ-SUjTX0KlvEgdP2B6JGkcomponents-hogcharts-piechart--long-label-tooltip--light:- hash: v1.k794b7964.083ff76dc306fc7cd2036b03d9d5545140cd24ba616951831fe210565a0bace7.q90E7qfNvWc7LpMhEVA5Wy8UiRWL8Zj_qK0GvU7aqZA+ hash: v1.k794b7964.76f4ca662585ef85568d30971ca3c3f2f0bc1067da927e6884080e4091e3da52.3aO3AeK9ytK5xR_qazf2L1Fpsmzg4S1j79lClnmy3t8components-hogcharts-piechart--no-hover-offset--dark:- hash: v1.k794b7964.36ec7ed69ab9a16b562f6d59643a450c26e48fa07f5630696f38594aa49c610b.1kVPOF_OuCp_r0Hokh0cNZ-K6kSC-9KW-5uhiGl-1OI+ hash: v1.k794b7964.24d046831aa8180891e26bb65ac7069917dadf17e42f573a2e548741570afbf3.RHkA9q4D3NFuxE4xSAhLEvT3xRpBZf680vnnOnd7pZ8components-hogcharts-piechart--no-hover-offset--light:- hash: v1.k794b7964.4ba748898ca2f36f7100332d96c4f3c51cd8a927253a21f187a2a4f3e93db95e.x_GSJSYhXipQxj4gd12Q4qwF5jiKopceWXXqdER9IzY+ hash: v1.k794b7964.42318dc943205955486a4e6442bfa866ece5fb59d8ea6fea0a81dee35958935e.b3p6cg-NjDO3nWqa8kWZJd4PC5L9UVJV_mjHdfA1pagcomponents-hogcharts-piechart--percent--dark:- hash: v1.k794b7964.503efa02ae97c5c60aa9adf056939622179a9864ce03906e86223027db2ce1b8.RWxBXw3OJ9zzy6F2aY-rp3EBJ2-HLfdOx2-E3k7oOsA+ hash: v1.k794b7964.90435be53b6484331125f0db7926381893370d2fa33e780fa7b70acedd4e1d75.s02bsLZicZFeHOViyoYt5DV4kLAJCYBjvFNJnqAdjUscomponents-hogcharts-piechart--percent--light:- hash: v1.k794b7964.e282bbc15ed4820ca911ef9e676f6819be7c86a62958c6ae8be3dd08fc5c44cf.FIU7hDUrHSgX6UtMev4GBzMyQi1jTrndbEGZOm_nUpg+ hash: v1.k794b7964.cf7b687f9b5c0c56d80cc4c217f48b07d8b3659c99094d7359791ee254e2f9f1.cVVk0GZ1cbj4AhCchW4muGg_SMPPNnr9HOVhTvOTwSYcomponents-hogcharts-piechart--pie-default--dark:- hash: v1.k794b7964.36ec7ed69ab9a16b562f6d59643a450c26e48fa07f5630696f38594aa49c610b.n2FYmxpqqzT6_FtrjqvjpdLLhlGH5xSktNBnEyN3xX8+ hash: v1.k794b7964.24d046831aa8180891e26bb65ac7069917dadf17e42f573a2e548741570afbf3.wgupmwLF22RR9v7VtmBje09o0vtv5VOd2BfxwNWl5EIcomponents-hogcharts-piechart--pie-default--light:- hash: v1.k794b7964.4ba748898ca2f36f7100332d96c4f3c51cd8a927253a21f187a2a4f3e93db95e.Iu2223knt2d5773R-s6_ke_oXweHsnv_nL-CmysPasI+ hash: v1.k794b7964.42318dc943205955486a4e6442bfa866ece5fb59d8ea6fea0a81dee35958935e.LHqZzLNWmyyjt2ASQBS_4fo9LhDTrNDDULZnSQMRrJEcomponents-hogcharts-piechart--single-slice--dark:hash: v1.k794b7964.92bc7531883a5830155772e9df2b63b96baf8611980c1195b66cb75716fe4a79.7zFlXhqZqOTrUg3V38lXuMA6YaGwCA_-s_CsBKtwgtMcomponents-hogcharts-piechart--single-slice--light:hash: v1.k794b7964.1a2540afa90064f951baa69e40405eb36459312978920ba46f2826cab097294a.JFioVV2KSnHa9Y-hREGuuT__I5ShHTvv8TgNVw7F0XUcomponents-hogcharts-piechart--with-breakdown-labels--dark:- hash: v1.k794b7964.e8aaf3e63d88d917b6511232aff85b4bf54f4c3b71fc267fde59a1170ba056a9.EL-FQ7Hqbd4FOdgbpZv2ynzzwJt2j6OQZkymgQXMC4U+ hash: v1.k794b7964.5202085eff2633fd9d2f43c2b1d01c0ff6708ca87aa8a104e051c0bba53b72b7.q_4nIqE5PItaSLZeF4aJNbjB14eSlTbLkX2JcZXgqVIcomponents-hogcharts-piechart--with-breakdown-labels--light:- hash: v1.k794b7964.811f8e01cbeeb97d8319a76668d33864b6be08a2b8f270e5980fe951fafbc1bb.UoRHUDWOOnMGSCQcBN8D5TwfE6LL3IG58n0wUC_WOwo+ hash: v1.k794b7964.0d2c1e4814a1414b2408dca7bcf8caab2c8ae39e313df9756d210e5dca04fba6.xQ4aCFRK6tR7nYCZNS7TKRDTD7qYqoZaUuY__-vfLBYcomponents-hogcharts-referenceline--fill-sides--dark:hash: v1.k794b7964.20d0fdc405a9dd537216032ada6fcef0a23581f114ba00501d4d7e39e773310b.jFz7FFT43BMvL4egnlYnYiV1a3SOjimiYoTRg-Iygs4components-hogcharts-referenceline--fill-sides--light:@@ -2228,6 +2228,14 @@ snapshots:hash: v1.k794b7964.9353b60c827a8e4563ac5b680274a55e4e9c1cefeebe765331636ae824e8d2d5.t75gvt_uBTQe_ABbuxW4JiJEW4CZk-IBfvJIkyTGlPUinsights-trendslinechart--single-series--light:hash: v1.k794b7964.e8d7c90005769112e971e55319b5e27731c8363aa977f21d5dbe8b9ec14b30ce.aaLz4Eg-X0FQkUCC9VXBjoVw902yotIdFJ4W5GzGu_8+ insights-trendspiechart--breakdown--dark:+ hash: v1.k794b7964.0a31833b6ea57d9f4600ccf6890fe628dcf649421b185cab228b64133cbf395f.AVix5li2YhjzEBTLUG_t-ykIUiNIn-JSmzkyjFnuO_A+ insights-trendspiechart--breakdown--light:+ hash: v1.k794b7964.d693e940dee065bffe724f5d53ee1913f60ebef68c1519d198ac2970b1938b00.3jEJqjovVqoTo-9Krah5534LJ2NznahddkdKV8Ycz3A+ insights-trendspiechart--percent-stack-breakdown--dark:+ hash: v1.k794b7964.e34f3d59389d536773130f86e3d548f45e8634417dd6e0cc8f7e1565625670e7.nPsI-tiuK_z1OTi2tHF4xRjtnkDonxppwaXv6-1PRzw+ insights-trendspiechart--percent-stack-breakdown--light:+ hash: v1.k794b7964.7d659bc5a97cfb229b7dce076b3d2524f8115622df0039ba55d0b259a9d1732a.d6C5OxdtwiAaERAZKaDiab_0N_51bFpw_hFP9aOUit4layout-feature-previews--basic--dark:hash: v1.k794b7964.65cb2d154c4f630bc48a9f6b45b24e641c97b4412ca5170e0c1de8bc5c7d759d.vu2XHwyh2oLXbqNS7NdZd2tABaC8nM7J0iJps6FVYl8layout-feature-previews--basic--light:diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.stories.tsx b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.stories.tsxnew file mode 100644index 000000000000..0fcf9769c50d--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.stories.tsx@@ -0,0 +1,147 @@+import { Meta, StoryObj } from '@storybook/react'+import { BindLogic } from 'kea'+import { useState } from 'react'++import { insightLogic } from 'scenes/insights/insightLogic'++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 type { InsightLogicProps, InsightShortId } from '~/types'++import { TrendsPieChart } from './TrendsPieChart'++type Story = StoryObj<{}>++const meta: Meta = {+ title: 'Insights/TrendsPieChart',+ component: TrendsPieChart,+ parameters: {+ layout: 'centered',+ mockDate: '2023-07-11',+ testOptions: { snapshotBrowsers: ['chromium'] },+ },+}+export default meta++let uniqueNode = 0++function Stage({ children }: { children: React.ReactNode }): JSX.Element {+ return (+ // eslint-disable-next-line react/forbid-dom-props+ <div style={{ height: 360, width: 480, display: 'flex', flexDirection: 'column' }}>{children}</div>+ )+}++function renderTrendsPieChart(insightFixture: any): JSX.Element {+ const [dashboardItemId] = useState(() => `TrendsPieChartStory.${uniqueNode++}` as InsightShortId)+ const cachedInsight = { ...insightFixture, short_id: dashboardItemId }++ 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}>+ <Stage>+ <TrendsPieChart />+ </Stage>+ </BindLogic>+ </BindLogic>+ )+}++const ACTION = {+ id: '$pageview',+ type: 'events',+ order: 0,+ name: '$pageview',+ custom_name: null,+ math: 'total',+ math_property: null,+ math_hogql: null,+ math_group_type_index: null,+ properties: {},+}++function breakdownSlice(label: string, aggregated_value: number): Record<string, any> {+ return {+ action: ACTION,+ label,+ count: 0,+ aggregated_value,+ data: [],+ labels: [],+ days: [],+ breakdown_value: label,+ filter: {+ date_from: '2023-07-04T00:00:00Z',+ date_to: '2023-07-10T23:59:59Z',+ display: 'ActionsPie',+ insight: 'TRENDS',+ interval: 'day',+ },+ }+}++function pieInsight(trendsFilter: Record<string, any>, shortId: string): Record<string, any> {+ return {+ id: 300,+ short_id: shortId,+ name: 'Pageviews by browser',+ derived_name: 'Pageview count',+ filters: {},+ last_refresh: '2023-07-11T12:00:00Z',+ refreshing: false,+ saved: true,+ is_sample: false,+ description: '',+ tags: [],+ favorited: false,+ created_at: '2023-07-11T12:00:00Z',+ updated_at: '2023-07-11T12:00:00Z',+ last_modified_at: '2023-07-11T12:00:00Z',+ dashboards: [],+ dashboard_tiles: [],+ result: [+ breakdownSlice('Chrome', 900),+ breakdownSlice('Safari', 500),+ breakdownSlice('Firefox', 220),+ breakdownSlice('Edge', 90),+ ],+ query: {+ kind: 'InsightVizNode',+ source: {+ dateRange: { date_from: '2023-07-04', date_to: '2023-07-10' },+ filterTestAccounts: false,+ interval: 'day',+ kind: 'TrendsQuery',+ series: [{ event: '$pageview', kind: 'EventsNode', math: 'total', name: '$pageview' }],+ trendsFilter,+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },+ version: 2,+ },+ full: true,+ },+ }+}++export const Breakdown: Story = {+ render: () => renderTrendsPieChart(pieInsight({ display: 'ActionsPie', showValuesOnSeries: true }, 'pieBreakdown')),+}++export const PercentStackBreakdown: Story = {+ render: () =>+ renderTrendsPieChart(+ pieInsight(+ { display: 'ActionsPie', showValuesOnSeries: true, showPercentStackView: true },+ 'piePercentStack'+ )+ ),+}diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.test.tsxnew file mode 100644index 000000000000..7513a91b8fed--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.test.tsx@@ -0,0 +1,72 @@+import '@testing-library/jest-dom'++import { cleanup, screen, waitFor } from '@testing-library/react'++import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'++import { FEATURE_FLAGS } from 'lib/constants'++import { NodeKind } from '~/queries/schema/schema-general'+import { buildTrendsQuery, personsModal, renderInsight } from '~/test/insight-testing'+import { ChartDisplayType } from '~/types'++let cleanupJsdom: () => void+let cleanupRaf: () => void++beforeEach(() => {+ cleanupJsdom = setupJsdom()+ cleanupRaf = setupSyncRaf()+})++afterEach(() => {+ personsModal.cleanupAll()+ cleanupRaf()+ cleanupJsdom()+ cleanup()+})++const HOG_CHARTS_FLAG = {+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_TRENDS]: true,+}++function sliceLabels(): string[] {+ return Array.from(document.querySelectorAll('[data-attr="hog-chart-pie-slice-label"]')).map(+ (el) => el.textContent ?? ''+ )+}++// Napped × hedgehog fixture: Spike 11, Thistle 4, Bramble 2, Prickles 2, Conker 0.+// Conker drops out (0% < the 5% slice-label threshold); total of the rest is 19,+// so percent mode renders 11/19, 4/19, 2/19, 2/19.+const pieByHedgehog = (trendsFilter: Record<string, unknown> = {}): ReturnType<typeof buildTrendsQuery> =>+ buildTrendsQuery({+ series: [{ kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' }],+ breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },+ trendsFilter: { display: ChartDisplayType.ActionsPie, showValuesOnSeries: true, ...trendsFilter },+ })++describe('TrendsPieChart (ActionsPie)', () => {+ it.each([+ {+ name: 'shows raw slice values when percent stack view is off',+ query: pieByHedgehog(),+ expectedLabels: ['11', '4', '2', '2'],+ },+ {+ name: 'formats slice values as percentages in percent stack view',+ query: pieByHedgehog({ showPercentStackView: true }),+ expectedLabels: ['57.9%', '21.1%', '10.5%', '10.5%'],+ },+ ])('$name', async ({ query, expectedLabels }) => {+ renderInsight({ query, featureFlags: HOG_CHARTS_FLAG })+ await screen.findByRole('img', { name: /pie chart with/i }, { timeout: 5000 })++ await waitFor(+ () => {+ expect(sliceLabels().length).toBeGreaterThan(0)+ },+ { timeout: 5000 }+ )+ expect([...sliceLabels()].sort()).toEqual([...expectedLabels].sort())+ })+})diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsxindex 40a0b53fb2e4..e3641f38ef96 100644--- a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx@@ -65,6 +65,8 @@ export function TrendsPieChart({formula,showValuesOnSeries,showLabelOnSeries,+ showPercentStackView,+ supportsPercentStackView,pieChartVizOptions,hasDataWarehouseSeries,querySource,@@ -74,6 +76,8 @@ export function TrendsPieChart({getTrendsHidden,} = useValues(trendsDataLogic(insightProps))+ const isPercentStackView = !!showPercentStackView && !!supportsPercentStackView+const resolvedGroupTypeLabel =context?.groupTypeLabel ??(labelGroupType === 'people'@@ -127,9 +131,10 @@ export function TrendsPieChart({() => ({showValueOnSlice: !!showValuesOnSeries,showLabelOnSlice: !!showLabelOnSeries,+ isPercent: isPercentStackView,disableHoverOffset: !!pieChartVizOptions?.disableHoverOffset,}),- [showValuesOnSeries, showLabelOnSeries, pieChartVizOptions?.disableHoverOffset]+ [showValuesOnSeries, showLabelOnSeries, isPercentStackView, pieChartVizOptions?.disableHoverOffset])// ActionsPie disables clicks entirely when the insight has data-warehouse series (see