: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(sql insights): render pie charts via quill-charts (#65021)
Sam Pennington5ecd299e13a0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex e3f150c4480d..cf19dd534392 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2508,6 +2508,18 @@ snapshots:hash: v1.k794b7964.2a58aadf641af52e00301410a651d409ef04e0e9f38de946d48e95654bc88247.kC7jND6q4E6sAipI3wKCvJGdsr0wgBbQpQjy1u-1my8insights-retentionlinechart--realistic-curve--light:hash: v1.k794b7964.4d86747ef6244c9dfda63e380938e7d5a2d4e8bb5643a689911b7c000da38439.Onr3r4WyIzDx9G1iqCIq-Y3n8HJi7d3D4N2VPP9VMow+ insights-sqlpiegraph--breakdown-colors--dark:+ hash: v1.k794b7964.470925de4820537085efce3e34dae137f86e39facc2ea154a9f16b5a5ca7c24d.d6RbyL3SlxGTdxtm-nf-oI1dpKT4rtbyTgRVaCCAM1U+ insights-sqlpiegraph--breakdown-colors--light:+ hash: v1.k794b7964.326aeff8c3f2a67f72991d488062e4a522d32b4abf7827a279517ac89cb4e996.rNMY2s51MqI8mbcI4QEYe6mOayeIn-CU439N9mvxua4+ insights-sqlpiegraph--default--dark:+ hash: v1.k794b7964.69d959b6da0714cb15749bda0154bf8e75c851096db4046d7649028cddfbfcec.5HrKjQ_i1oGPCe2C4PjqSSvt5Uo1Ut-mGVX7UwGZh4I+ insights-sqlpiegraph--default--light:+ hash: v1.k794b7964.f5a009e13082094b0195af966cde19b289974ac8c54261b0871d86ed962fb7b2.aliPJsCIazzCphQ7X-7ZIbBAsKee1OeDrO1Un_p003Q+ insights-sqlpiegraph--with-legend--dark:+ hash: v1.k794b7964.fcb21fd79db53b62394f5a12551c0918b081cba21206788e8fe229ac23f04c7e.yOYHdOAHOMIgzoS7IzahzFGk0KJQqIz_A2kF4Y-mvTY+ insights-sqlpiegraph--with-legend--light:+ hash: v1.k794b7964.56fd0f5cbef5514f7e10d5a38d0a376c399f4d520059c1e12ce4ef557d37bffd.MYW8k6KAEnxVE7EOAPqhhoEqdoltzjuy7G0gRPJuq40insights-stickinessbarchart--stacked--dark:hash: v1.k794b7964.06d7987531ee38109e865aabbe9e5cc197d030ff62e5ecfc18a7f1c7f9184703.blTIjpW25Ww909yC_cJKt6jm1-ZQo_LmovewZTUyTroinsights-stickinessbarchart--stacked--light:diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.test.tsindex 6b1fb732adbd..2f55067dc0fd 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.test.ts+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.test.ts@@ -27,7 +27,8 @@ describe('sqlChartComponentFor', () => {['line', ChartDisplayType.ActionsLineGraph, true, 'SqlLineGraph'],['bar', ChartDisplayType.ActionsBar, true, 'SqlBarGraph'],['line with the flag off', ChartDisplayType.ActionsLineGraph, false, 'LegacyLineGraph'],- ['an unsupported visualization', ChartDisplayType.ActionsPie, true, 'LegacyLineGraph'],+ // Pie is not routed here — it has its own wrapper (see PieChart.test.tsx).+ ['pie (handled by the PieChart wrapper, not here)', ChartDisplayType.ActionsPie, true, 'LegacyLineGraph'],])('routes %s to the right component', (_name, visualizationType, newChartsEnabled, expected) => {expect(sqlChartComponentFor(baseProps(visualizationType), newChartsEnabled).name).toBe(expected)})diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.test.tsxnew file mode 100644index 000000000000..da568c538000--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.test.tsx@@ -0,0 +1,58 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'++import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { initKeaTests } from '~/test/init'++import { AxisSeries } from '../../dataVisualizationLogic'+import { PieChart, PieChartProps } from './PieChart'++let cleanupJsdom: () => void+let cleanupRaf: () => void++beforeEach(() => {+ initKeaTests()+ cleanupJsdom = setupJsdom()+ cleanupRaf = setupSyncRaf()+})++afterEach(() => {+ cleanupRaf()+ cleanupJsdom()+ cleanup()+})++const props: PieChartProps = {+ uniqueKey: 'pie-wrapper-test',+ xData: {+ column: { name: 'category', type: { name: 'STRING', isNumerical: false }, label: 'category', dataIndex: 0 },+ data: ['alpha', 'beta'],+ } as AxisSeries<string>,+ yData: [+ {+ column: { name: 'value', type: { name: 'INTEGER', isNumerical: true }, label: 'value', dataIndex: 1 },+ data: [60, 40],+ settings: {},+ },+ ],+ chartSettings: {},+}++describe('PieChart wrapper', () => {+ it('routes to the quill SqlPieGraph when the quill-sql-charts flag is on', async () => {+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_SQL_CHARTS], {+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_SQL_CHARTS]: true,+ })++ render(<PieChart {...props} />)++ // The quill PieChart canvas carries this accessible name; the legacy chart.js path does not.+ expect(await screen.findByRole('img', { name: /pie chart with/i }, { timeout: 5000 })).toBeInTheDocument()+ })+})diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.tsxindex a8bbbbb69f33..4d69887ec4cf 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.tsx@@ -1,18 +1,22 @@import clsx from 'clsx'-import { BindLogic } from 'kea'+import { BindLogic, useValues } from 'kea'import { useMemo } from 'react'import { LemonColorGlyph } from '@posthog/lemon-ui'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { insightLogic } from 'scenes/insights/insightLogic'import { PieChart as InsightPieChart } from 'scenes/insights/views/LineGraph/PieChart'import { ChartSettings } from '~/queries/schema/schema-general'-import { GraphType, InsightLogicProps } from '~/types'+import { ChartDisplayType, GraphType, InsightLogicProps } from '~/types'import { AxisSeries, formatDataWithSettings } from '../../dataVisualizationLogic'import { AxisBreakdownSeries } from '../seriesBreakdownLogic'-import { buildPieSlices, formatPieSliceCount } from './sqlPieGraphAdapter'+import { LineGraphProps } from './LineGraph'+import { SqlPieGraph } from './SqlPieGraph'+import { buildPieSlices, canRenderSqlPieGraph, formatPieSliceCount } from './sqlPieGraphAdapter'export interface PieChartProps {xData: AxisSeries<string> | null@@ -23,7 +27,27 @@ export interface PieChartProps {uniqueKey: string}-export function PieChart({+export function PieChart(props: PieChartProps): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)+ const newChartsEnabled = !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_SQL_CHARTS]++ const sqlPieProps: LineGraphProps = {+ xData: props.xData,+ yData: props.yData,+ visualizationType: ChartDisplayType.ActionsPie,+ chartSettings: props.chartSettings,+ presetChartHeight: props.presetChartHeight,+ className: props.className,+ }++ if (newChartsEnabled && canRenderSqlPieGraph(sqlPieProps)) {+ return <SqlPieGraph {...sqlPieProps} />+ }++ return <LegacyPieChart {...props} />+}++function LegacyPieChart({xData,yData,chartSettings,diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.stories.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.stories.tsxnew file mode 100644index 000000000000..9a5d0960b83e--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.stories.tsx@@ -0,0 +1,87 @@+import { Meta, StoryObj } from '@storybook/react'+import { ReactNode } from 'react'++import { ChartSettings } from '~/queries/schema/schema-general'+import { ChartDisplayType } from '~/types'++import { AxisSeries } from '../../dataVisualizationLogic'+import { AxisBreakdownSeries } from '../seriesBreakdownLogic'+import { LineGraphProps } from './LineGraph'+import { SqlPieGraph } from './SqlPieGraph'++const meta: Meta<typeof SqlPieGraph> = {+ title: 'Insights/SqlPieGraph',+ component: SqlPieGraph,+ parameters: {+ layout: 'centered',+ testOptions: { snapshotBrowsers: ['chromium'] },+ },+}+export default meta++type Story = StoryObj<typeof SqlPieGraph>++const xData: AxisSeries<string> = {+ column: { name: 'month', type: { name: 'STRING', isNumerical: false }, label: 'month', dataIndex: 0 },+ data: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],+}++const singleSeries: AxisSeries<number | null>[] = [+ {+ column: { name: 'events', type: { name: 'INTEGER', isNumerical: true }, label: 'events', dataIndex: 1 },+ data: [4200, 1800, 620, 410, 80],+ settings: {},+ },+]++const breakdownSeries: AxisBreakdownSeries<number | null>[] = [+ { name: 'Chrome', breakdownValue: 'Chrome', data: [4200], settings: { display: { color: '#4287f5' } } },+ { name: 'Safari', breakdownValue: 'Safari', data: [1800], settings: { display: { color: '#34a853' } } },+ { name: 'Firefox', breakdownValue: 'Firefox', data: [620], settings: { display: { color: '#fbbc05' } } },+ { name: 'Edge', breakdownValue: 'Edge', data: [410], settings: { display: { color: '#ea4335' } } },+]++// SqlPieGraph fills its flex parent, so the story needs a column container with a definite height —+// otherwise the chart resolves to height 0 and quill paints a 0-size canvas (mirrors TrendsPieChart).+function Stage({ children }: { children: ReactNode }): JSX.Element {+ // eslint-disable-next-line react/forbid-dom-props+ return <div style={{ height: 420, width: 760, display: 'flex', flexDirection: 'column' }}>{children}</div>+}++const render = (props: LineGraphProps): JSX.Element => (+ <Stage>+ <SqlPieGraph {...props} />+ </Stage>+)++const baseSettings: ChartSettings = { showValuesOnSeries: true, showPieTotal: true }++export const Default: Story = {+ render: () =>+ render({+ xData,+ yData: singleSeries,+ visualizationType: ChartDisplayType.ActionsPie,+ chartSettings: baseSettings,+ }),+}++export const WithLegend: Story = {+ render: () =>+ render({+ xData,+ yData: singleSeries,+ visualizationType: ChartDisplayType.ActionsPie,+ chartSettings: { ...baseSettings, showLegend: true },+ }),+}++export const BreakdownColors: Story = {+ render: () =>+ render({+ xData,+ yData: breakdownSeries,+ visualizationType: ChartDisplayType.ActionsPie,+ chartSettings: { ...baseSettings, showLegend: true },+ }),+}diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.test.tsxnew file mode 100644index 000000000000..c471773d7c9c--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.test.tsx@@ -0,0 +1,111 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen, waitFor } from '@testing-library/react'++import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'++import { ChartSettings } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import { ChartDisplayType } from '~/types'++import { AxisSeries } from '../../dataVisualizationLogic'+import { AxisBreakdownSeries } from '../seriesBreakdownLogic'+import { LineGraphProps } from './LineGraph'+import { SqlPieGraph } from './SqlPieGraph'++let cleanupJsdom: () => void+let cleanupRaf: () => void++beforeEach(() => {+ initKeaTests()+ cleanupJsdom = setupJsdom()+ cleanupRaf = setupSyncRaf()+})++afterEach(() => {+ cleanupRaf()+ cleanupJsdom()+ cleanup()+})++const xData: AxisSeries<string> = {+ column: { name: 'category', type: { name: 'STRING', isNumerical: false }, label: 'category', dataIndex: 0 },+ data: ['alpha', 'beta', 'gamma', 'delta'],+}++const yData = (data: (number | null)[]): AxisSeries<number | null>[] => [+ {+ column: { name: 'value', type: { name: 'INTEGER', isNumerical: true }, label: 'value', dataIndex: 1 },+ data,+ settings: {},+ },+]++const baseProps = (chartSettings: ChartSettings, data: (number | null)[]): LineGraphProps => ({+ xData,+ yData: yData(data),+ visualizationType: ChartDisplayType.ActionsPie,+ chartSettings,+})++// On-slice value labels are static overlay nodes (not pointer-driven), so they steer clear of the+// quill PieChart's flaky hover/click interaction tests.+function sliceLabels(): string[] {+ return Array.from(document.querySelectorAll('[data-attr="hog-chart-pie-slice-label"]')).map((el) => el.textContent!)+}++describe('SqlPieGraph', () => {+ it('renders a value label per positive slice and the aggregation total', async () => {+ render(<SqlPieGraph {...baseProps({ showPieTotal: true }, [40, 30, 20, 10])} />)++ await screen.findByRole('img', { name: /pie chart with/i }, { timeout: 5000 })+ await waitFor(+ () => {+ expect(sliceLabels().length).toBeGreaterThan(0)+ },+ { timeout: 5000 }+ )++ expect([...sliceLabels()].sort()).toEqual(['10', '20', '30', '40'])+ expect(screen.getByText('100')).toBeInTheDocument()+ })++ it('renders the side legend with per-slice values and shares', () => {+ // The legend is plain DOM (rendered for both responsive layouts), so it needs no canvas paint.+ render(<SqlPieGraph {...baseProps({ showLegend: true }, [60, 40, 0, 0])} />)++ expect(screen.getAllByText('alpha').length).toBeGreaterThan(0)+ expect(screen.getAllByText('60.0%').length).toBeGreaterThan(0)+ expect(screen.getAllByText('40.0%').length).toBeGreaterThan(0)+ })++ it('shows the empty state when there are no positive values', () => {+ render(<SqlPieGraph {...baseProps({}, [0, 0, null, 0])} />)++ expect(screen.getByText('Pie charts require at least one positive value.')).toBeInTheDocument()+ })++ it('colors breakdown slices from per-breakdown resultCustomizations', () => {+ // One slice per breakdown series; the legend swatch color must come from+ // settings.display.color (resultCustomizations), not the palette default.+ const breakdownYData: AxisBreakdownSeries<number | null>[] = [+ { name: 'first', breakdownValue: 'first', data: [3, 2], settings: { display: { color: '#aa0000' } } },+ { name: 'second', breakdownValue: 'second', data: [4, 1], settings: { display: { color: '#00aa00' } } },+ ]+ render(+ <SqlPieGraph+ xData={xData}+ yData={breakdownYData}+ visualizationType={ChartDisplayType.ActionsPie}+ chartSettings={{ showLegend: true }}+ />+ )++ const swatchColors = Array.from(document.querySelectorAll<HTMLElement>('.LemonColorGlyph')).map(+ (el) => el.style.color+ )+ expect(screen.getAllByText('first').length).toBeGreaterThan(0)+ expect(swatchColors).toContain('rgb(170, 0, 0)')+ expect(swatchColors).toContain('rgb(0, 170, 0)')+ })+})diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsxnew file mode 100644index 000000000000..2d144735caf1--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx@@ -0,0 +1,160 @@+import clsx from 'clsx'+import { useValues } from 'kea'+import { useCallback, useMemo } from 'react'++import { LemonColorGlyph } from '@posthog/lemon-ui'+import { PieChart, TooltipSurface, TooltipSwatch } from '@posthog/quill-charts'+import type { PieChartConfig, TooltipContext } from '@posthog/quill-charts'++import { buildTheme } from 'lib/charts/utils/theme'++import { themeLogic } from '~/layout/navigation-3000/themeLogic'++import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'++import { formatDataWithSettings } from '../../dataVisualizationLogic'+import { LineGraphProps } from './LineGraph'+import { buildPieSeries, buildPieSlices, formatPieSliceCount } from './sqlPieGraphAdapter'++const handleChartError = makeChartErrorHandler('sql-pie-chart')++/**+ * SQL pie graph on @posthog/quill-charts' {@link PieChart}, gated behind the+ * `product-analytics-quill-sql-charts` flag (see {@link sqlChartComponentFor}). The chart core lives+ * in quill; the aggregation total and side legend stay here as chrome, matching the legacy wrapper.+ */+export const SqlPieGraph = ({+ xData,+ yData,+ chartSettings,+ presetChartHeight,+ className,+}: LineGraphProps): JSX.Element => {+ const { isDarkModeOn } = useValues(themeLogic)+ // isDarkModeOn invalidates the memo so buildTheme() re-reads CSS vars on dark-mode toggle.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ const theme = useMemo(() => buildTheme(), [isDarkModeOn])++ const slices = useMemo(() => buildPieSlices(xData, yData), [xData, yData])+ const formattingSettings = yData[0]?.settings+ const series = useMemo(() => buildPieSeries(slices), [slices])+ const total = useMemo(() => slices.reduce((sum, slice) => sum + slice.value, 0), [slices])++ const showLegend = chartSettings.showLegend ?? false+ const showPieTotal = chartSettings.showPieTotal ?? true++ const valueFormatter = useCallback(+ (value: number) => String(formatDataWithSettings(value, formattingSettings) ?? value),+ [formattingSettings]+ )++ const pieConfig: PieChartConfig = useMemo(+ () => ({ showValueOnSlice: chartSettings.showValuesOnSeries ?? true }),+ [chartSettings.showValuesOnSeries]+ )++ const renderTooltip = useCallback(+ (ctx: TooltipContext) => {+ const entry = ctx.seriesData[0]+ if (!entry) {+ return null+ }+ return (+ <TooltipSurface>+ <div className="flex items-center gap-2">+ <TooltipSwatch color={entry.color} />+ <span className="font-semibold">{entry.series.label}</span>+ <strong className="ml-auto">+ {formatPieSliceCount(entry.value, total, formattingSettings)}+ </strong>+ </div>+ </TooltipSurface>+ )+ },+ [total, formattingSettings]+ )++ if (!slices.length) {+ return (+ <div className={clsx(className, 'rounded bg-surface-primary flex flex-1 items-center justify-center p-6')}>+ <span className="text-secondary text-sm">Pie charts require at least one positive value.</span>+ </div>+ )+ }++ const chart = (+ <PieChart+ series={series}+ theme={theme}+ config={pieConfig}+ tooltip={renderTooltip}+ valueFormatter={valueFormatter}+ dataAttr="sql-pie-chart"+ onError={handleChartError}+ />+ )++ const totalDisplay = showPieTotal ? (+ <div className="pt-4 text-center shrink-0">+ <div className="text-5xl font-bold">{valueFormatter(total)}</div>+ </div>+ ) : null++ const legend = showLegend ? (+ <div className="w-full xl:w-80 shrink-0 border border-border rounded bg-surface-secondary overflow-visible xl:overflow-auto">+ <div className="divide-y divide-border">+ {slices.map((slice) => {+ const percent = total > 0 ? ((slice.value / total) * 100).toFixed(1) : '0.0'++ return (+ <div key={slice.label} className="flex items-center justify-between gap-3 px-3 py-2 text-sm">+ <div className="flex items-center gap-2 min-w-0">+ <LemonColorGlyph color={slice.color} className="shrink-0" />+ <span className="truncate">{slice.label}</span>+ </div>+ <div className="text-right shrink-0">+ <div className="font-semibold">{valueFormatter(slice.value)}</div>+ <div className="text-xs text-secondary">{percent}%</div>+ </div>+ </div>+ )+ })}+ </div>+ </div>+ ) : null++ return (+ <div+ className={clsx(className, 'rounded bg-surface-primary flex flex-1 p-4 gap-4', {+ 'h-[60vh]': presetChartHeight,+ 'h-full': !presetChartHeight,+ })}+ >+ {!showLegend ? (+ <div className="flex flex-1 min-h-0">+ <div className="flex flex-1 flex-col min-h-0">+ <div className="flex flex-col flex-1 min-h-[18rem]">{chart}</div>+ {totalDisplay}+ </div>+ </div>+ ) : (+ <>+ <div className="flex flex-col gap-4 w-full xl:hidden">+ <div className="flex flex-col">+ <div className="flex flex-col h-[18rem]">{chart}</div>+ {totalDisplay}+ </div>+ {legend}+ </div>+ <div className="hidden xl:flex flex-1 gap-4 min-h-0">+ <div className="flex flex-1 flex-col min-h-0">+ <div className="flex flex-col flex-1 min-h-[18rem]">{chart}</div>+ {totalDisplay}+ </div>+ {legend}+ </div>+ </>+ )}+ </div>+ )+}