: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
chore(surveys): migrate question charts to quill-charts (#61828)
Sam Pennington3a2d9263d7ef
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 9849f2bdc8fd..f3cb7841e335 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6202,6 +6202,10 @@ snapshots:hash: v1.k794b7964.0499534d1b67d9b3b48ae43ee6627d36eb452c79b27cdd6e53daa29f0abe93b7.Wh7gm5MVLvsgHcuppxP86CAhF3C71ptNCCvdBcFI1HEscenes-app-surveys--new-survey-with-text-question-description-that-does-not-render-html--light:hash: v1.k794b7964.da042d485c41af9617b77ef27301d4a4a2b693e8e301199ee0ab270d289b023a.ygKH5sOow6s1H1TEjac-I9uemRPLdaaqpAcFFvmOWnE+ scenes-app-surveys--survey-results--dark:+ hash: v1.k794b7964.d035e85baf25fe53e7f074e1945dd6107ac0b1a2703fa3ce1891cb6f90c345fa.sbcVjtrEKjMCcKsIpGCfKHuIA4VLcAajM1VXwpHvsj0+ scenes-app-surveys--survey-results--light:+ hash: v1.k794b7964.869a49a1266fd06617df093fa385f5653adb4fc0f262e68d0d101ae1dc3608ad.8ZKi3wgRoogG1SjlHyYEP_obfC0gmBdZjk7jmFYfMWoscenes-app-surveys--surveys-global-settings--dark:hash: v1.k794b7964.427cfe9d37f22f4541a7229a96d8911f0a952d21249e07b33e7ee6e52a29c5ba.G5JF2D7oalvStlE95BvDNYjoSVukCgnScl8oOVxIOSsscenes-app-surveys--surveys-global-settings--light:diff --git a/frontend/src/scenes/surveys/Surveys.stories.tsx b/frontend/src/scenes/surveys/Surveys.stories.tsxindex e51d379d4d9f..1e789152304d 100644--- a/frontend/src/scenes/surveys/Surveys.stories.tsx+++ b/frontend/src/scenes/surveys/Surveys.stories.tsx@@ -15,6 +15,7 @@ import {PropertyFilterType,PropertyOperator,Survey,+ SurveyEventName,SurveyQuestionType,SurveySchedule,SurveyType,@@ -201,6 +202,113 @@ const MOCK_RESPONSES_COUNT = {'0187c279-bcae-0000-34f5-4f121921f006': 25,}+// Survey whose results actually load, so the question-visualization charts render.+const MOCK_SURVEY_WITH_RESULTS: Survey = {+ id: '0187c279-bcae-0000-34f5-4f121921f099',+ name: 'survey with results',+ description: 'survey whose question charts render',+ type: SurveyType.Popover,+ created_at: '2023-05-01T10:04:37.977401Z',+ created_by: {+ id: 1,+ uuid: '01863799-062b-0000-8a61-b2842d5f8642',+ distinct_id: 'Sopz9Z4NMIfXGlJe6W1XF98GOqhHNui5J5eRe0tBGTE',+ first_name: 'Employee 427',+ email: '[email protected]',+ },+ questions: [+ {+ type: SurveyQuestionType.Rating,+ question: 'How likely are you to recommend us to a friend?',+ id: 'q-rating',+ display: 'number',+ scale: 10,+ lowerBoundLabel: 'Not likely',+ upperBoundLabel: 'Very likely',+ },+ {+ type: SurveyQuestionType.SingleChoice,+ question: 'What is your favorite feature?',+ id: 'q-single',+ choices: ['Dashboards', 'Insights', 'Experiments', 'Surveys'],+ },+ {+ type: SurveyQuestionType.MultipleChoice,+ question: "We're sorry to see you go. What's your reason for unsubscribing?",+ id: 'q-multi',+ choices: [+ 'I no longer need the product',+ 'I found a better product',+ 'I found the product too difficult to use',+ 'Other',+ ],+ },+ ],+ conditions: null,+ linked_flag: null,+ linked_flag_id: null,+ targeting_flag: null,+ targeting_flag_filters: undefined,+ appearance: { backgroundColor: 'white', submitButtonColor: '#2C2C2C' },+ start_date: '2023-05-02T10:04:37.977401Z',+ end_date: null,+ archived: false,+ responses_limit: null,+ iteration_count: null,+ iteration_frequency_days: null,+ schedule: SurveySchedule.Once,+ user_access_level: AccessControlLevel.Editor,+}++// Rows from the consolidated aggregate query: [question_id, label, count].+const MOCK_SURVEY_AGGREGATE_RESULTS = {+ columns: ['question_id', 'label', 'cnt'],+ types: [+ ['question_id', 'String'],+ ['label', 'String'],+ ['cnt', 'UInt64'],+ ],+ results: [+ // Rating (NPS scale 0-10) — mix of detractors / passives / promoters+ ['q-rating', '10', 32],+ ['q-rating', '9', 28],+ ['q-rating', '8', 14],+ ['q-rating', '7', 9],+ ['q-rating', '6', 5],+ ['q-rating', '5', 4],+ ['q-rating', '3', 2],+ ['q-rating', '0', 3],+ // Single choice+ ['q-single', 'Dashboards', 30],+ ['q-single', 'Insights', 25],+ ['q-single', 'Experiments', 12],+ ['q-single', 'Surveys', 8],+ // Multiple choice (with the synthetic total row the processor expects)+ ['q-multi', 'I no longer need the product', 20],+ ['q-multi', 'I found a better product', 15],+ ['q-multi', 'I found the product too difficult to use', 10],+ ['q-multi', 'Other', 5],+ ['q-multi', '__total__', 40],+ ],+}++// Rows from the base-stats query: [event_name, total_count, unique_persons, first_seen, last_seen].+const MOCK_SURVEY_BASE_STATS = {+ columns: ['event_name', 'total_count', 'unique_persons', 'first_seen', 'last_seen'],+ types: [+ ['event_name', 'String'],+ ['total_count', 'UInt64'],+ ['unique_persons', 'UInt64'],+ ['first_seen', "Nullable(DateTime64(6, 'UTC'))"],+ ['last_seen', "Nullable(DateTime64(6, 'UTC'))"],+ ],+ results: [+ [SurveyEventName.SHOWN, 120, 110, '2023-05-02T10:00:00Z', '2023-06-20T10:00:00Z'],+ [SurveyEventName.SENT, 75, 70, '2023-05-02T11:00:00Z', '2023-06-20T09:00:00Z'],+ [SurveyEventName.DISMISSED, 18, 17, '2023-05-03T10:00:00Z', '2023-06-19T10:00:00Z'],+ ],+}+const meta: Meta = {component: App,title: 'Scenes-App/Surveys',@@ -434,6 +542,44 @@ export const SurveyView: Story = {},}+export const SurveyResults: Story = {+ parameters: {+ pageUrl: urls.survey(MOCK_SURVEY_WITH_RESULTS.id),+ testOptions: {+ waitForSelector: '[data-attr="survey-rating"] canvas',+ },+ },+ decorators: [+ mswDecorator({+ get: {+ [`/api/projects/:team_id/surveys/${MOCK_SURVEY_WITH_RESULTS.id}/`]: MOCK_SURVEY_WITH_RESULTS,+ [`/api/projects/:team_id/surveys/${MOCK_SURVEY_WITH_RESULTS.id}/archived-response-uuids/`]: [],+ '/api/projects/:team_id/surveys/responses_count/': {+ ...MOCK_RESPONSES_COUNT,+ [MOCK_SURVEY_WITH_RESULTS.id]: 75,+ },+ '/api/environments/:team_id/hog_functions/': { count: 0, results: [], next: null },+ },+ post: {+ '/api/environments/:team_id/query/:kind/': async (req, res, ctx) => {+ const body = await req.json()+ const sql: string = body?.query?.query ?? ''+ if (sql.includes('question_id, label, cnt')) {+ return res(ctx.json(MOCK_SURVEY_AGGREGATE_RESULTS))+ }+ if (sql.includes('BASE STATS')) {+ return res(ctx.json(MOCK_SURVEY_BASE_STATS))+ }+ if (sql.includes('DISMISSED AND SENT COUNT')) {+ return res(ctx.json({ results: [[60]] }))+ }+ return res(ctx.json({ results: [] }))+ },+ },+ }),+ ],+}+export const SurveyNotFound: Story = {tags: ['test-skip'],parameters: {diff --git a/frontend/src/scenes/surveys/components/question-visualizations/MultipleChoiceBarChart.tsx b/frontend/src/scenes/surveys/components/question-visualizations/MultipleChoiceBarChart.tsxnew file mode 100644index 000000000000..da362f82e019--- /dev/null+++ b/frontend/src/scenes/surveys/components/question-visualizations/MultipleChoiceBarChart.tsx@@ -0,0 +1,117 @@+import { useValues } from 'kea'+import { useCallback, useMemo } from 'react'++import { BarChart, ValueLabels } from '@posthog/quill-charts'+import type { BarChartConfig, Series, TooltipContext } from '@posthog/quill-charts'++import { buildTheme } from 'lib/charts/utils/theme'+import {+ ChoiceTooltip,+ ChoiceTooltipContextData,+} from 'scenes/surveys/components/question-visualizations/questionVizTooltips'+import { formatCountWithPercentage } from 'scenes/surveys/components/question-visualizations/questionVizTransforms'++import { themeLogic } from '~/layout/navigation-3000/themeLogic'+import { ChoiceQuestionResponseData } from '~/types'++const CATEGORY_LABEL_WIDTH = 280+// Gap between the bar tip and its value label.+const VALUE_LABEL_OFFSET = 6++interface Props {+ chartData: ChoiceQuestionResponseData[]+ totalResponses: number+ activeChoiceLabel: string | null+ barColors: string[]+ tooltipContextByIndex: ChoiceTooltipContextData[]+ onBarClick: (index: number) => void+}++// series/labels/config identities gate the chart's internal memos and canvas redraws, so they+// must stay stable across the unrelated re-renders surveyLogic emits during a results requery —+// rebuilding them every render makes the chart visibly flash while a filter reloads.+export function MultipleChoiceBarChart({+ chartData,+ totalResponses,+ activeChoiceLabel,+ barColors,+ tooltipContextByIndex,+ onBarClick,+}: Props): JSX.Element {+ const { isDarkModeOn } = useValues(themeLogic)+ const theme = useMemo(() => buildTheme(), [isDarkModeOn])++ // Bars encode the share of respondents who picked each choice against a fixed 0–100% domain;+ // counts surface in the labels and tooltip. Per-bar overrides carry the colors — the series+ // color is just the fallback.+ const series = useMemo<Series[]>(+ () => [+ {+ key: 'multiple-choice',+ label: 'Share of respondents',+ data: chartData.map((d) => (totalResponses > 0 ? (d.value / totalResponses) * 100 : 0)),+ color: barColors[0],+ bars: chartData.map((_, i) => ({ color: barColors[i] })),+ },+ ],+ [chartData, totalResponses, barColors]+ )++ // Synthetic band keys keep bars distinct even if two choices share a label; the choice text is+ // rendered through the category-axis formatter instead.+ const labels = useMemo(() => chartData.map((_, i) => String(i)), [chartData])++ const config = useMemo<BarChartConfig>(+ () => ({+ axisOrientation: 'horizontal',+ barLayout: 'grouped',+ hideXAxis: true,+ showGrid: false,+ showAxisLines: false,+ maxCategoryLabelWidth: CATEGORY_LABEL_WIDTH,+ xTickFormatter: (_label, index) => chartData[index]?.label ?? '',+ margins: { top: 4, right: 20, bottom: 4 },+ bars: {+ cornerRadius: 3,+ minBandSize: 32,+ valueDomain: [0, 100],+ },+ tooltip: { placement: 'cursor' },+ }),+ [chartData]+ )++ const renderTooltip = useCallback(+ (ctx: TooltipContext): JSX.Element => (+ <ChoiceTooltip+ ctx={ctx}+ chartData={chartData}+ tooltipContextByIndex={tooltipContextByIndex}+ activeChoiceLabel={activeChoiceLabel}+ />+ ),+ [chartData, tooltipContextByIndex, activeChoiceLabel]+ )++ const valueFormatter = useCallback(+ (_value: number, _seriesIndex: number, dataIndex: number): string =>+ formatCountWithPercentage(chartData[dataIndex]?.value ?? 0, totalResponses),+ [chartData, totalResponses]+ )++ return (+ <div className="pl-4">+ <BarChart+ series={series}+ labels={labels}+ config={config}+ theme={theme}+ tooltip={renderTooltip}+ onPointClick={({ dataIndex }) => onBarClick(dataIndex)}+ dataAttr="survey-multiple-choice"+ >+ <ValueLabels valueFormatter={valueFormatter} offset={VALUE_LABEL_OFFSET} />+ </BarChart>+ </div>+ )+}diff --git a/frontend/src/scenes/surveys/components/question-visualizations/MultipleChoiceQuestionViz.test.tsx b/frontend/src/scenes/surveys/components/question-visualizations/MultipleChoiceQuestionViz.test.tsxnew file mode 100644index 000000000000..43bb8364b633--- /dev/null+++ b/frontend/src/scenes/surveys/components/question-visualizations/MultipleChoiceQuestionViz.test.tsx@@ -0,0 +1,145 @@+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'+import { BindLogic } from 'kea'+import { router } from 'kea-router'++import { dimensions, ensureJsdom } from '@posthog/quill-charts/testing'++import { MultipleChoiceQuestionViz } from 'scenes/surveys/components/question-visualizations/MultipleChoiceQuestionViz'+import { surveyLogic } from 'scenes/surveys/surveyLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import {+ ChoiceQuestionResponseData,+ MultipleSurveyQuestion,+ PropertyFilterType,+ PropertyOperator,+ SurveyQuestionType,+} from '~/types'++const QUESTION: MultipleSurveyQuestion = {+ id: 'q1',+ type: SurveyQuestionType.MultipleChoice,+ question: 'Which features do you use?',+ choices: ['Feature A', 'Feature B'],+}++const RESPONSE_DATA: ChoiceQuestionResponseData[] = [+ { label: 'Feature A', value: 3, isPredefined: true },+ { label: 'Feature B', value: 2, isPredefined: true },+]++describe('MultipleChoiceQuestionViz double-click filtering', () => {+ let logic: ReturnType<typeof surveyLogic.build>++ afterEach(() => {+ cleanup()+ jest.useRealTimers()+ })++ beforeEach(() => {+ ensureJsdom()+ initKeaTests()+ // answerFilters is a persisted reducer and setAnswerFilters writes ?answerFilters=… to the+ // URL — clear both so a previous test's applied filter doesn't leak into the next mount.+ localStorage.clear()+ router.actions.push('/surveys/test-survey')+ useMocks({+ get: {+ '/api/projects/:team/surveys/': () => [200, { count: 0, results: [], next: null, previous: null }],+ '/api/projects/:team/surveys/test-survey/': () => [+ 200,+ {+ id: 'test-survey',+ name: 'Test survey',+ type: 'popover',+ questions: [QUESTION],+ start_date: '2026-01-01T00:00:00Z',+ end_date: null,+ archived: false,+ appearance: {},+ conditions: null,+ created_at: '2026-01-01T00:00:00Z',+ },+ ],+ '/api/projects/:team/surveys/test-survey/archived-response-uuids/': () => [200, []],+ '/api/projects/:team/surveys/responses_count/': () => [200, {}],+ },+ post: {+ '/api/environments/:team_id/query/': () => [200, { results: [] }],+ },+ })+ logic = surveyLogic({ id: 'test-survey' })+ logic.mount()+ })++ function renderViz(): HTMLElement {+ render(+ <BindLogic logic={surveyLogic} props={{ id: 'test-survey' }}>+ <MultipleChoiceQuestionViz+ question={QUESTION}+ questionIndex={0}+ responseData={RESPONSE_DATA}+ totalResponses={5}+ />+ </BindLogic>+ )+ const chart = document.querySelector('[data-attr="survey-multiple-choice"]')+ if (!(chart instanceof HTMLElement)) {+ throw new Error('chart wrapper not rendered')+ }+ return chart+ }++ // Horizontal chart: bands run down the y axis, one row per choice (sorted by value, so+ // row 0 is "Feature A"). Quill resolves clicks through the last hover position.+ function clickRow(chart: HTMLElement, rowIndex: number): void {+ const rowStep = dimensions.plotHeight / RESPONSE_DATA.length+ fireEvent.mouseMove(chart, {+ clientX: dimensions.plotLeft + dimensions.plotWidth * 0.2,+ clientY: dimensions.plotTop + rowStep * (rowIndex + 0.5),+ })+ fireEvent.click(chart)+ }++ it('arms on the first click without applying a filter', () => {+ const chart = renderViz()++ clickRow(chart, 0)++ expect(screen.getByText('Click "Feature A" again to filter by this choice.')).toBeTruthy()+ expect(logic.values.answerFilters).toEqual([])+ })++ it('applies the answer filter on the second click of a double-click', () => {+ const chart = renderViz()++ clickRow(chart, 0)+ clickRow(chart, 0)++ expect(logic.values.answerFilters).toEqual([+ {+ key: '$survey_response_q1',+ type: PropertyFilterType.Event,+ operator: PropertyOperator.IContains,+ value: 'Feature A',+ },+ ])+ expect(screen.getByText(/Showing only "Feature A" responses/)).toBeTruthy()+ })++ it('clears the armed state after the timeout without applying a filter', () => {+ jest.useFakeTimers()+ const chart = renderViz()++ clickRow(chart, 0)+ expect(screen.getByText('Click "Feature A" again to filter by this choice.')).toBeTruthy()++ act(() => {+ jest.advanceTimersByTime(2600)+ })++ expect(screen.getByText('Double-click an option to filter by that choice.')).toBeTruthy()+ expect(logic.values.answerFilters).toEqual([])+ })+})diff --git a/frontend/src/scenes/surveys/components/question-visualizations/MultipleChoiceQuestionViz.tsx b/frontend/src/scenes/surveys/components/question-visualizations/MultipleChoiceQuestionViz.tsxindex 1e2218d9c2f6..477ddcec7b4c 100644--- a/frontend/src/scenes/surveys/components/question-visualizations/MultipleChoiceQuestionViz.tsx+++ b/frontend/src/scenes/surveys/components/question-visualizations/MultipleChoiceQuestionViz.tsx@@ -1,31 +1,24 @@-import { BindLogic, useActions, useValues } from 'kea'+import { useActions, useValues } from 'kea'import { useEffect, useMemo, useState } from 'react'-import { hexToRGBA } from 'lib/utils'-import { insightLogic } from 'scenes/insights/insightLogic'-import { LineGraph } from 'scenes/insights/views/LineGraph/LineGraph'+import { MultipleChoiceBarChart } from 'scenes/surveys/components/question-visualizations/MultipleChoiceBarChart'import { OpenQuestionSummaryV2 } from 'scenes/surveys/components/question-visualizations/OpenQuestionSummaryV2'+import { computeBarColors } from 'scenes/surveys/components/question-visualizations/questionVizTransforms'import { CHART_INSIGHTS_COLORS } from 'scenes/surveys/components/question-visualizations/util'import { VirtualizedResponseList } from 'scenes/surveys/components/question-visualizations/VirtualizedResponseList'import { surveyLogic } from 'scenes/surveys/surveyLogic'import { getSurveyIdBasedResponseKey } from 'scenes/surveys/utils'+import { themeLogic } from '~/layout/navigation-3000/themeLogic'import {ChoiceQuestionResponseData,EventPropertyFilter,- GraphPointPayload,- GraphType,- InsightLogicProps,MultipleSurveyQuestion,OpenQuestionResponseData,PropertyFilterType,PropertyOperator,} from '~/types'-const insightProps: InsightLogicProps = {- dashboardItemId: `new-survey`,-}-interface Props {question: MultipleSurveyQuestionquestionIndex: number@@ -86,6 +79,7 @@ export function MultipleChoiceQuestionViz({}: Props): JSX.Element | null {const { answerFilters } = useValues(surveyLogic)const { setAnswerFilters } = useActions(surveyLogic)+ const { isDarkModeOn } = useValues(themeLogic)const { chartData, openEndedResponses } = useMemo((): ProcessedData => {const predefinedResponses = responseData.filter((d) => d.isPredefined)@@ -148,43 +142,29 @@ export function MultipleChoiceQuestionViz({const highlightedChoiceLabel = activeChoiceLabel || armedChoiceLabel- const barColors = useMemo(- () =>- chartData.map((entry, i) => {- const baseColor = CHART_INSIGHTS_COLORS[i % CHART_INSIGHTS_COLORS.length]-- if (!highlightedChoiceLabel || entry.label === highlightedChoiceLabel) {- return baseColor- }-- return hexToRGBA(baseColor, activeChoiceLabel ? 0.22 : 0.35)- }),- [activeChoiceLabel, chartData, highlightedChoiceLabel]- )+ const barColors = useMemo(() => {+ const baseColors = chartData.map((_, i) => CHART_INSIGHTS_COLORS[i % CHART_INSIGHTS_COLORS.length])+ return computeBarColors(+ baseColors,+ chartData.map((d) => d.label),+ highlightedChoiceLabel,+ !!activeChoiceLabel,+ isDarkModeOn+ )+ }, [activeChoiceLabel, chartData, highlightedChoiceLabel, isDarkModeOn])const tooltipContextByIndex = useMemo((): TooltipContext[] => {const totalSelections = chartData.reduce((sum, d) => sum + d.value, 0)- let currentRank = 0- let previousValue: number | null = null- return chartData.map((entry, index) => {- if (entry.value !== previousValue) {- currentRank = index + 1- previousValue = entry.value- }-- return {- rank: currentRank,- respondentPercentage: totalResponses > 0 ? ((entry.value / totalResponses) * 100).toFixed(1) : '0.0',- selectionPercentage: totalSelections > 0 ? ((entry.value / totalSelections) * 100).toFixed(1) : '0.0',- }- })+ // chartData is sorted by value, so the row position is the rank — no tie-skipping,+ // which read as the tooltip showing the "wrong" number.+ return chartData.map((entry, index) => ({+ rank: index + 1,+ respondentPercentage: totalResponses > 0 ? ((entry.value / totalResponses) * 100).toFixed(1) : '0.0',+ selectionPercentage: totalSelections > 0 ? ((entry.value / totalSelections) * 100).toFixed(1) : '0.0',+ }))}, [chartData, totalResponses])- const tooltipCountLabel = (value: number): JSX.Element => {- return <span className="font-semibold tabular-nums">{value}</span>- }-const upsertChoiceAnswerFilter = (choiceLabel: string | null): void => {if (!responseFilterKey) {return@@ -217,7 +197,7 @@ export function MultipleChoiceQuestionViz({setAnswerFilters(updatedFilters)}- const handleChoiceBarClick = ({ index }: GraphPointPayload): void => {+ const applyChoiceClick = (index: number): void => {if (!responseFilterKey) {return}@@ -251,96 +231,14 @@ export function MultipleChoiceQuestionViz({return (<div className="space-y-4"><div className="border rounded py-4 max-h-[600px] overflow-y-auto">- <BindLogic logic={insightLogic} props={insightProps}>- <LineGraph- inSurveyView={true}- hideYAxis={true}- hideXAxis={true}- showValuesOnSeries={true}- labelGroupType={1}- data-attr="survey-multiple-choice"- type={GraphType.HorizontalBar}- formula="-"- onClick={handleChoiceBarClick}- tooltip={{- showHeader: false,- hideColorCol: true,- groupTypeLabel: 'responses',- getInspectLabel: (referenceDatum) => {- const hoveredChoiceLabel = referenceDatum- ? String(- referenceDatum.breakdown_value ??- chartData[referenceDatum.dataIndex]?.label ??- ''- )- : null-- if (activeChoiceLabel && hoveredChoiceLabel === activeChoiceLabel) {- return 'Click to clear filter'- }-- if (activeChoiceLabel) {- return 'Click to switch filter'- }-- return 'Double click to filter'- },- renderSeries: (_value, datum) => {- const tooltipContext = tooltipContextByIndex[datum.dataIndex]- const optionLabel = String(- datum.breakdown_value ?? chartData[datum.dataIndex]?.label ?? datum.label ?? ''- )-- if (!tooltipContext) {- return <span className="font-medium">{optionLabel}</span>- }-- return (- <div className="space-y-0.5">- <div className="flex items-center gap-2 leading-tight">- <span className="font-semibold">{optionLabel}</span>- <span className="text-xs text-muted-alt">- #{tooltipContext.rank} of {chartData.length}- </span>- </div>- <div className="text-xs text-secondary leading-tight">- <span className="font-semibold text-primary">- {tooltipContext.respondentPercentage}%- </span>{' '}- respondents- <span className="mx-1 text-muted-alt">•</span>- <span className="font-medium text-primary">- {tooltipContext.selectionPercentage}%- </span>{' '}- of all selected options- </div>- </div>- )- },- renderCount: tooltipCountLabel,- }}- datasets={[- {- id: 1,- label: 'Number of responses',- barPercentage: 0.8,- minBarLength: 2,- data: chartData.map((d) => d.value),- labels: chartData.map((d) => d.label),- breakdownValues: chartData.map((d) => d.label),- backgroundColor: barColors,- borderColor: barColors,- hoverBackgroundColor: barColors,- },- ]}- labels={chartData.map((d) => d.label)}- datalabelFormatter={(value) => {- const total = totalResponses || 1- const percentage = ((value / total) * 100).toFixed(1)- return `${value} (${percentage}%)`- }}- />- </BindLogic>+ <MultipleChoiceBarChart+ chartData={chartData}+ totalResponses={totalResponses}+ activeChoiceLabel={activeChoiceLabel}+ barColors={barColors}+ tooltipContextByIndex={tooltipContextByIndex}+ onBarClick={applyChoiceClick}+ /></div>{responseFilterKey && (<div className="text-xs text-muted text-center">diff --git a/frontend/src/scenes/surveys/components/question-visualizations/RatingBarChart.tsx b/frontend/src/scenes/surveys/components/question-visualizations/RatingBarChart.tsxnew file mode 100644index 000000000000..66b7ea52efc5--- /dev/null+++ b/frontend/src/scenes/surveys/components/question-visualizations/RatingBarChart.tsx@@ -0,0 +1,95 @@+import { useValues } from 'kea'+import { useCallback, useMemo } from 'react'++import { BarChart, ValueLabels } from '@posthog/quill-charts'+import type { BarChartConfig, Series, TooltipContext } from '@posthog/quill-charts'++import { buildTheme } from 'lib/charts/utils/theme'+import { NpsBucketMeta, RatingTooltip } from 'scenes/surveys/components/question-visualizations/questionVizTooltips'+import { formatCountWithPercentage } from 'scenes/surveys/components/question-visualizations/questionVizTransforms'++import { themeLogic } from '~/layout/navigation-3000/themeLogic'+import { ChoiceQuestionResponseData } from '~/types'++// Room above each bar tip for the value label's height, so it floats rather than overlapping the bar.+const VALUE_LABEL_PADDING = 28++interface Props {+ data: ChoiceQuestionResponseData[]+ chartLabels: string[]+ totalResponses: number+ barColors: string[]+ activeRatingLabel: string | null+ tooltipContextByIndex: { respondentPercentage: string }[]+ npsBucketByIndex: (NpsBucketMeta | null)[]+ onBarClick: (index: number) => void+}++export function RatingBarChart({+ data,+ chartLabels,+ totalResponses,+ barColors,+ activeRatingLabel,+ tooltipContextByIndex,+ npsBucketByIndex,+ onBarClick,+}: Props): JSX.Element {+ const { isDarkModeOn } = useValues(themeLogic)+ const theme = useMemo(() => buildTheme(), [isDarkModeOn])++ const series = useMemo<Series[]>(+ () => [+ {+ key: 'survey-rating',+ label: 'Number of responses',+ data: chartLabels.map((_, i) => data[i]?.value ?? 0),+ color: barColors[0],+ bars: chartLabels.map((_, i) => ({ color: barColors[i] })),+ },+ ],+ [chartLabels, data, barColors]+ )++ const config = useMemo<BarChartConfig>(+ () => ({+ hideYAxis: true,+ bars: { bandPadding: 0.2, valuePadding: VALUE_LABEL_PADDING },+ }),+ []+ )++ const renderTooltip = useCallback(+ (ctx: TooltipContext): JSX.Element => (+ <RatingTooltip+ ctx={ctx}+ chartLabels={chartLabels}+ tooltipContextByIndex={tooltipContextByIndex}+ npsBucketByIndex={npsBucketByIndex}+ activeRatingLabel={activeRatingLabel}+ />+ ),+ [chartLabels, tooltipContextByIndex, npsBucketByIndex, activeRatingLabel]+ )++ const valueFormatter = useCallback(+ (value: number): string => formatCountWithPercentage(value, totalResponses),+ [totalResponses]+ )++ return (+ <div className="relative h-full w-full flex flex-col">+ <BarChart+ series={series}+ labels={chartLabels}+ config={config}+ theme={theme}+ tooltip={renderTooltip}+ onPointClick={({ dataIndex }) => onBarClick(dataIndex)}+ dataAttr="survey-rating"+ >+ <ValueLabels valueFormatter={valueFormatter} />+ </BarChart>+ </div>+ )+}diff --git a/frontend/src/scenes/surveys/components/question-visualizations/RatingQuestionViz.tsx b/frontend/src/scenes/surveys/components/question-visualizations/RatingQuestionViz.tsxindex b8ac26dca642..4f0fe45da280 100644--- a/frontend/src/scenes/surveys/components/question-visualizations/RatingQuestionViz.tsx+++ b/frontend/src/scenes/surveys/components/question-visualizations/RatingQuestionViz.tsx@@ -1,4 +1,4 @@-import { BindLogic, useActions, useValues } from 'kea'+import { useActions, useValues } from 'kea'import { useMemo } from 'react'import { IconInfo, IconThumbsDown, IconThumbsUp } from '@posthog/icons'@@ -9,9 +9,8 @@ import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { IntervalFilterStandalone } from 'lib/components/IntervalFilter'import { dayjs } from 'lib/dayjs'import { IconOpenInNew } from 'lib/lemon-ui/icons'-import { hexToRGBA } from 'lib/utils'-import { insightLogic } from 'scenes/insights/insightLogic'-import { LineGraph } from 'scenes/insights/views/LineGraph/LineGraph'+import { computeBarColors } from 'scenes/surveys/components/question-visualizations/questionVizTransforms'+import { RatingBarChart } from 'scenes/surveys/components/question-visualizations/RatingBarChart'import { CHART_INSIGHTS_COLORS } from 'scenes/surveys/components/question-visualizations/util'import { StackedBar, StackedBarSegment, StackedBarSkeleton } from 'scenes/surveys/components/StackedBar'import {@@ -31,15 +30,13 @@ import {} from 'scenes/surveys/utils'import { urls } from 'scenes/urls'+import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { Query } from '~/queries/Query/Query'import { InsightVizNode, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'import {ChartDisplayType,ChoiceQuestionProcessedResponses,EventPropertyFilter,- GraphPointPayload,- GraphType,- InsightLogicProps,PropertyFilterType,PropertyOperator,RatingSurveyQuestion,@@ -48,10 +45,6 @@ import {SurveyEventProperties,} from '~/types'-const insightProps: InsightLogicProps = {- dashboardItemId: `new-survey`,-}-function createNPSTrendSeries(values: string[],label: string,@@ -509,6 +502,7 @@ export function RatingQuestionViz({ question, questionIndex, processedData }: Prconst { answerFilters } = useValues(surveyLogic)const { setAnswerFilters } = useActions(surveyLogic)+ const { isDarkModeOn } = useValues(themeLogic)const { data } = processedDataconst npsBreakdown = calculateNpsBreakdownFromProcessedData(processedData)const thumbsBreakdown = isThumbQuestion(question) ? calculateThumbsBreakdown(processedData) : null@@ -525,10 +519,6 @@ export function RatingQuestionViz({ question, questionIndex, processedData }: Pr[data, totalResponses])- const tooltipCountLabel = (value: number): JSX.Element => {- return <span className="font-semibold tabular-nums">{value}</span>- }-const responseFilterKey = question.id ? getSurveyIdBasedResponseKey(question.id) : nullconst currentQuestionFilter = useMemo(@@ -558,18 +548,23 @@ export function RatingQuestionViz({ question, questionIndex, processedData }: Prconst highlightedRatingLabel = activeRatingLabelconst ratingBarColors = useMemo((): string[] => {- return chartLabels.map((label) => {- const baseColor = isNpsRatingQuestion- ? NPS_BUCKET_COLORS[getNpsBucketByRatingLabel(label).bucket]- : barColor-- if (!highlightedRatingLabel || label === highlightedRatingLabel) {- return baseColor- }+ const baseColors = chartLabels.map((label) =>+ isNpsRatingQuestion ? NPS_BUCKET_COLORS[getNpsBucketByRatingLabel(label).bucket] : barColor+ )+ return computeBarColors(baseColors, chartLabels, highlightedRatingLabel, !!activeRatingLabel, isDarkModeOn)+ }, [activeRatingLabel, barColor, chartLabels, highlightedRatingLabel, isNpsRatingQuestion, isDarkModeOn])- return hexToRGBA(baseColor, activeRatingLabel ? 0.22 : 0.35)- })- }, [activeRatingLabel, barColor, chartLabels, highlightedRatingLabel, isNpsRatingQuestion])+ const npsBucketByIndex = useMemo(+ () =>+ chartLabels.map((label) => {+ if (!isNpsRatingQuestion) {+ return null+ }+ const { bucket, label: bucketLabel } = getNpsBucketByRatingLabel(label)+ return { label: bucketLabel, textClass: NPS_BUCKET_TEXT_CLASS[bucket] }+ }),+ [chartLabels, isNpsRatingQuestion]+ )const upsertRatingAnswerFilter = (ratingLabel: string | null): void => {if (!responseFilterKey) {@@ -603,7 +598,7 @@ export function RatingQuestionViz({ question, questionIndex, processedData }: PrsetAnswerFilters(updatedFilters)}- const handleRatingBarClick = ({ index }: GraphPointPayload): void => {+ const applyRatingClick = (index: number): void => {if (!responseFilterKey) {return}@@ -628,88 +623,16 @@ export function RatingQuestionViz({ question, questionIndex, processedData }: Pr<><div className="flex flex-col gap-1"><div className="h-50 border rounded pt-8">- <div className="relative h-full w-full">- <BindLogic logic={insightLogic} props={insightProps}>- <LineGraph- inSurveyView={true}- hideYAxis={true}- showValuesOnSeries={true}- labelGroupType={1}- data-attr="survey-rating"- type={GraphType.Bar}- hideAnnotations={true}- formula="-"- onClick={handleRatingBarClick}- tooltip={{- showHeader: false,- hideColorCol: true,- groupTypeLabel: 'responses',- getInspectLabel: (referenceDatum) => {- const hoveredRatingLabel = referenceDatum- ? (chartLabels[referenceDatum.dataIndex] ?? null)- : null-- if (activeRatingLabel && hoveredRatingLabel === activeRatingLabel) {- return 'Click to clear filter'- }-- if (activeRatingLabel) {- return 'Click to switch filter'- }-- return 'Click to filter'- },- renderSeries: (_value, datum) => {- const ratingLabel = chartLabels[datum.dataIndex] ?? String(datum.dataIndex + 1)- const context = tooltipContextByIndex[datum.dataIndex]- const npsBucket = isNpsRatingQuestion- ? getNpsBucketByRatingLabel(ratingLabel)- : null-- return (- <div className="space-y-0.5">- <div className="flex items-center gap-2 leading-tight">- <span className="font-semibold">Rating {ratingLabel}</span>- {npsBucket && (- <span- className={`text-xs ${NPS_BUCKET_TEXT_CLASS[npsBucket.bucket]}`}- >- {npsBucket.label}- </span>- )}- </div>- <div className="text-xs text-secondary leading-tight">- <span className="font-semibold text-primary">- {context?.respondentPercentage ?? '0.0'}%- </span>{' '}- respondents- </div>- </div>- )- },- renderCount: tooltipCountLabel,- }}- datasets={[- {- id: 1,- label: 'Number of responses',- barPercentage: 0.8,- data: data.map((d) => d.value),- labels: chartLabels,- backgroundColor: ratingBarColors,- borderColor: ratingBarColors,- hoverBackgroundColor: ratingBarColors,- },- ]}- labels={chartLabels}- datalabelFormatter={(value) => {- const total = totalResponses || 1- const percentage = ((value / total) * 100).toFixed(1)- return `${value} (${percentage}%)`- }}- />- </BindLogic>- </div>+ <RatingBarChart+ data={data}+ chartLabels={chartLabels}+ totalResponses={totalResponses}+ barColors={ratingBarColors}+ activeRatingLabel={activeRatingLabel}+ tooltipContextByIndex={tooltipContextByIndex}+ npsBucketByIndex={npsBucketByIndex}+ onBarClick={applyRatingClick}+ /></div><div className="flex flex-row justify-between"><div className="text-secondary pl-10">{question.lowerBoundLabel}</div>diff --git a/frontend/src/scenes/surveys/components/question-visualizations/questionVizTooltips.tsx b/frontend/src/scenes/surveys/components/question-visualizations/questionVizTooltips.tsxnew file mode 100644index 000000000000..5e0385aae90e--- /dev/null+++ b/frontend/src/scenes/surveys/components/question-visualizations/questionVizTooltips.tsx@@ -0,0 +1,113 @@+import { TooltipSurface, TooltipSwatch } from '@posthog/quill-charts'+import type { TooltipContext } from '@posthog/quill-charts'++import { ChoiceQuestionResponseData } from '~/types'++export interface ChoiceTooltipContextData {+ rank: number+ respondentPercentage: string+ selectionPercentage: string+}++export interface NpsBucketMeta {+ label: string+ textClass: string+}++function TooltipRow({ label, value }: { label: string; value: string }): JSX.Element {+ return (+ <div className="flex justify-between gap-4">+ <span className="opacity-60">{label}</span>+ <span className="font-semibold tabular-nums">{value}</span>+ </div>+ )+}++export function ChoiceTooltip({+ ctx,+ chartData,+ tooltipContextByIndex,+ activeChoiceLabel,+}: {+ ctx: TooltipContext+ chartData: ChoiceQuestionResponseData[]+ tooltipContextByIndex: ChoiceTooltipContextData[]+ activeChoiceLabel: string | null+}): JSX.Element {+ const optionLabel = chartData[ctx.dataIndex]?.label ?? ctx.seriesData[0]?.series.label ?? ''+ const tooltipContext = tooltipContextByIndex[ctx.dataIndex]+ // The series carries percentages (the bar axis is share of respondents) — counts live in chartData.+ const value = chartData[ctx.dataIndex]?.value ?? 0+ const swatchColor = ctx.seriesData[0]?.color++ if (!tooltipContext) {+ return (+ <TooltipSurface>+ <span className="font-semibold">{optionLabel}</span>+ </TooltipSurface>+ )+ }++ let inspectLabel = 'Double click to filter'+ if (activeChoiceLabel && optionLabel === activeChoiceLabel) {+ inspectLabel = 'Click to clear filter'+ } else if (activeChoiceLabel) {+ inspectLabel = 'Click to switch filter'+ }++ return (+ <TooltipSurface>+ <div className="flex items-center gap-2 font-semibold mb-1">+ {swatchColor && <TooltipSwatch color={swatchColor} />}+ <span>{optionLabel}</span>+ <span className="font-normal opacity-60">+ #{tooltipContext.rank} of {chartData.length}+ </span>+ </div>+ <TooltipRow label="Responses" value={String(value)} />+ <TooltipRow label="Respondents" value={`${tooltipContext.respondentPercentage}%`} />+ <TooltipRow label="Of selected options" value={`${tooltipContext.selectionPercentage}%`} />+ <div className="mt-1 opacity-60">{inspectLabel}</div>+ </TooltipSurface>+ )+}++export function RatingTooltip({+ ctx,+ chartLabels,+ tooltipContextByIndex,+ npsBucketByIndex,+ activeRatingLabel,+}: {+ ctx: TooltipContext+ chartLabels: string[]+ tooltipContextByIndex: { respondentPercentage: string }[]+ npsBucketByIndex: (NpsBucketMeta | null)[]+ activeRatingLabel: string | null+}): JSX.Element {+ const ratingLabel = chartLabels[ctx.dataIndex] ?? String(ctx.dataIndex + 1)+ const context = tooltipContextByIndex[ctx.dataIndex]+ const value = ctx.seriesData[0]?.value ?? 0+ const npsBucket = npsBucketByIndex[ctx.dataIndex]+ const swatchColor = ctx.seriesData[0]?.color++ let inspectLabel = 'Click to filter'+ if (activeRatingLabel && ratingLabel === activeRatingLabel) {+ inspectLabel = 'Click to clear filter'+ } else if (activeRatingLabel) {+ inspectLabel = 'Click to switch filter'+ }++ return (+ <TooltipSurface>+ <div className="flex items-center gap-2 font-semibold mb-1">+ {swatchColor && <TooltipSwatch color={swatchColor} />}+ <span>Rating {ratingLabel}</span>+ {npsBucket && <span className={`font-normal ${npsBucket.textClass}`}>{npsBucket.label}</span>}+ </div>+ <TooltipRow label="Responses" value={String(value)} />+ <TooltipRow label="Respondents" value={`${context?.respondentPercentage ?? '0.0'}%`} />+ <div className="mt-1 opacity-60">{inspectLabel}</div>+ </TooltipSurface>+ )+}diff --git a/frontend/src/scenes/surveys/components/question-visualizations/questionVizTransforms.test.ts b/frontend/src/scenes/surveys/components/question-visualizations/questionVizTransforms.test.tsnew file mode 100644index 000000000000..55981789bbda--- /dev/null+++ b/frontend/src/scenes/surveys/components/question-visualizations/questionVizTransforms.test.ts@@ -0,0 +1,54 @@+import { computeBarColors } from './questionVizTransforms'++const BLUE = '#1D4BFF'+const PINK = '#CD0F74'+const TEAL = '#43827E'++function mixed(hex: string, keep: number, towards: number): string {+ const r = parseInt(hex.slice(1, 3), 16)+ const g = parseInt(hex.slice(3, 5), 16)+ const b = parseInt(hex.slice(5, 7), 16)+ const mix = (channel: number): number => Math.round(channel * keep + towards * (1 - keep))+ return `rgb(${mix(r)},${mix(g)},${mix(b)})`+}++describe('computeBarColors', () => {+ const labels = ['a', 'b', 'c']+ const baseColors = [BLUE, PINK, TEAL]++ it('returns the base colors unchanged when nothing is highlighted', () => {+ expect(computeBarColors(baseColors, labels, null, false, false)).toEqual(baseColors)+ })++ it('keeps the highlighted bar at full color and dims the rest with the active strength', () => {+ expect(computeBarColors(baseColors, labels, 'b', true, false)).toEqual([+ mixed(BLUE, 0.4, 255),+ PINK,+ mixed(TEAL, 0.4, 255),+ ])+ })++ it('uses the lighter armed strength when no filter is active', () => {+ expect(computeBarColors(baseColors, labels, 'a', false, false)).toEqual([+ BLUE,+ mixed(PINK, 0.55, 255),+ mixed(TEAL, 0.55, 255),+ ])+ })++ it('dims toward black in dark mode so dimmed bars stay opaque over the bar track', () => {+ expect(computeBarColors(baseColors, labels, 'b', true, true)).toEqual([+ mixed(BLUE, 0.4, 0),+ PINK,+ mixed(TEAL, 0.4, 0),+ ])+ })++ it('dims every bar when the highlighted label matches none of them', () => {+ expect(computeBarColors(baseColors, labels, 'missing', true, false)).toEqual([+ mixed(BLUE, 0.4, 255),+ mixed(PINK, 0.4, 255),+ mixed(TEAL, 0.4, 255),+ ])+ })+})diff --git a/frontend/src/scenes/surveys/components/question-visualizations/questionVizTransforms.ts b/frontend/src/scenes/surveys/components/question-visualizations/questionVizTransforms.tsnew file mode 100644index 000000000000..76d11d062ea9--- /dev/null+++ b/frontend/src/scenes/surveys/components/question-visualizations/questionVizTransforms.ts@@ -0,0 +1,40 @@+import { hexToRGB } from 'lib/utils'++// Share of the base color kept for non-highlighted bars. Stronger dim when a filter is actually+// applied (active), lighter when a choice is only "armed" for a follow-up click. Keeps must stay+// clearly above the bar track's ~0.14-0.32 alpha tint so dimmed bars don't melt into the track.+const ACTIVE_DIM_KEEP = 0.4+const ARMED_DIM_KEEP = 0.55++// Opaque dim: mix toward the surface (black in dark mode, white in light) instead of alpha, so+// dimmed bars stay solid over the hatched bar track rendered behind them.+function dimColor(hex: string, keep: number, isDarkModeOn: boolean): string {+ const { r, g, b } = hexToRGB(hex)+ const towards = isDarkModeOn ? 0 : 255+ const mix = (channel: number): number => Math.round(channel * keep + towards * (1 - keep))+ return `rgb(${mix(r)},${mix(g)},${mix(b)})`+}++// Per-bar colors, shared by the rating and multiple-choice charts: non-highlighted bars are dimmed.+export function computeBarColors(+ baseColors: string[],+ labels: string[],+ highlightedLabel: string | null,+ hasActiveFilter: boolean,+ isDarkModeOn: boolean+): string[] {+ return labels.map((label, index) => {+ const baseColor = baseColors[index]++ if (!highlightedLabel || label === highlightedLabel) {+ return baseColor+ }++ return dimColor(baseColor, hasActiveFilter ? ACTIVE_DIM_KEEP : ARMED_DIM_KEEP, isDarkModeOn)+ })+}++export function formatCountWithPercentage(value: number, total: number): string {+ const percentage = ((value / (total || 1)) * 100).toFixed(1)+ return `${value} (${percentage}%)`+}