: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(surveys): redesign response row with focused expansion panel (#58511)
Lucas Faria106fc50aa9d7
diff --git a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyResponseExpandedRow.tsx b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyResponseExpandedRow.tsxnew file mode 100644index 000000000000..ecb7fb8359e1--- /dev/null+++ b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyResponseExpandedRow.tsx@@ -0,0 +1,182 @@+import { useValues } from 'kea'++import { IconArchive, IconCode, IconGlobe, IconLaptop, IconPin } from '@posthog/icons'+import { LemonDivider, LemonTag, Link } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import ViewRecordingButton, { ViewRecordingButtonVariant } from 'lib/components/ViewRecordingButton/ViewRecordingButton'+import { countryCodeToFlag } from 'lib/utils/geography/country'+import { PersonDisplay } from 'scenes/persons/PersonDisplay'+import { getThumbIcon } from 'scenes/surveys/hooks/useSurveyResponseColumns'+import { surveyLogic } from 'scenes/surveys/surveyLogic'+import { getSurveyResponseValue, isScaleTwoRating } from 'scenes/surveys/utils'++import { EventType, SurveyEventProperties, SurveyQuestion } from '~/types'++function prettyUrl(url: string): string {+ try {+ const parsed = new URL(url)+ return `${parsed.host}${parsed.pathname}`.replace(/\/$/, '') || parsed.host+ } catch {+ return url.replace(/^https?:\/\//, '')+ }+}++function findEventInRow(result: unknown): EventType | null {+ if (!Array.isArray(result)) {+ return null+ }+ for (const cell of result) {+ if (+ cell &&+ typeof cell === 'object' &&+ !Array.isArray(cell) &&+ 'properties' in cell &&+ typeof (cell as { properties: unknown }).properties === 'object'+ ) {+ return cell as EventType+ }+ }+ return null+}++function formatAnswer(value: unknown): string {+ if (Array.isArray(value)) {+ return value.join(', ')+ }+ if (value === null || value === undefined) {+ return ''+ }+ return String(value)+}++function AnswerDisplay({ question, value }: { question: SurveyQuestion; value: unknown }): JSX.Element {+ if (isScaleTwoRating(question) && (value == '1' || value == '2')) {+ return (+ <span className="text-sm flex items-center gap-1">+ {getThumbIcon(value)}+ Thumbs {value == '1' ? 'up' : 'down'}+ </span>+ )+ }+ return <p className="text-sm whitespace-pre-wrap m-0">{formatAnswer(value)}</p>+}++function MetaItem({ icon, children }: { icon?: JSX.Element; children: React.ReactNode }): JSX.Element {+ return (+ <span className="flex items-center gap-1 min-w-0">+ {icon && <span className="shrink-0 flex items-center">{icon}</span>}+ <span className="truncate">{children}</span>+ </span>+ )+}++export function SurveyResponseExpandedRow({ result }: { result: unknown }): JSX.Element | null {+ const event = findEventInRow(result)+ const { survey, archivedResponseUuids } = useValues(surveyLogic)++ if (!event) {+ return null+ }++ const properties = event.properties ?? {}+ const currentUrl = typeof properties.$current_url === 'string' ? properties.$current_url : null+ const sessionId = typeof properties.$session_id === 'string' ? properties.$session_id : undefined+ const browser = typeof properties.$browser === 'string' ? properties.$browser : null+ const os = typeof properties.$os === 'string' ? properties.$os : null+ const deviceType = typeof properties.$device_type === 'string' ? properties.$device_type : null+ const deviceLine = [browser, os, deviceType].filter(Boolean).join(' · ')+ const city = typeof properties.$geoip_city_name === 'string' ? properties.$geoip_city_name : null+ const country = typeof properties.$geoip_country_name === 'string' ? properties.$geoip_country_name : null+ const countryCode = typeof properties.$geoip_country_code === 'string' ? properties.$geoip_country_code : null+ const locationLine = [city, country].filter(Boolean).join(', ')+ const lib = typeof properties.$lib === 'string' ? properties.$lib : null+ const libVersion = typeof properties.$lib_version === 'string' ? properties.$lib_version : null+ const libraryLine = [lib, libVersion].filter(Boolean).join(' ')+ const iteration = properties[SurveyEventProperties.SURVEY_ITERATION]+ const isPartial =+ properties[SurveyEventProperties.SURVEY_COMPLETED] === false ||+ properties[SurveyEventProperties.SURVEY_PARTIALLY_COMPLETED] === true+ const isArchived = event.uuid ? archivedResponseUuids?.has(event.uuid) : false++ const responses: { questionIndex: number; question: SurveyQuestion; value: unknown }[] = []+ if (survey?.questions) {+ survey.questions.forEach((q, index) => {+ const value = getSurveyResponseValue(properties, index, q.id)+ if (value !== undefined) {+ responses.push({ questionIndex: index, question: q, value })+ }+ })+ }++ return (+ <div className="sticky left-0 w-full max-w-[min(56rem,calc(100vw-2rem))] px-4 py-3 flex flex-col gap-4">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 text-xs text-secondary">+ <PersonDisplay+ person={{ distinct_id: event.distinct_id, properties: event.person?.properties }}+ withIcon="xs"+ noEllipsis={false}+ />+ {event.timestamp && <TZLabel time={event.timestamp} />}+ {sessionId && (+ <ViewRecordingButton+ sessionId={sessionId}+ timestamp={event.timestamp}+ variant={ViewRecordingButtonVariant.Link}+ checkRecordingExists+ />+ )}+ {isPartial && (+ <LemonTag type="warning" size="small">+ Partial+ </LemonTag>+ )}+ {isArchived && (+ <LemonTag type="muted" size="small" icon={<IconArchive />}>+ Archived+ </LemonTag>+ )}+ {iteration !== undefined && iteration !== null && (+ <MetaItem>+ <span className="text-muted">Iteration</span> {String(iteration)}+ </MetaItem>+ )}+ </div>++ {responses.length > 0 && (+ <div className="flex flex-col gap-3">+ {responses.map(({ questionIndex, question, value }) => (+ <div key={questionIndex} className="flex flex-col gap-1">+ <span className="text-xs text-secondary font-semibold">{question.question}</span>+ <AnswerDisplay question={question} value={value} />+ </div>+ ))}+ </div>+ )}++ <LemonDivider className="my-0" />++ <div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-xs text-secondary">+ {currentUrl && (+ <Link+ to={currentUrl}+ target="_blank"+ title={currentUrl}+ className="flex items-center gap-1 max-w-xs min-w-0"+ >+ <IconGlobe className="shrink-0" />+ <span className="truncate">{prettyUrl(currentUrl)}</span>+ </Link>+ )}+ {deviceLine && <MetaItem icon={<IconLaptop />}>{deviceLine}</MetaItem>}+ {locationLine && (+ <MetaItem icon={<IconPin />}>+ {countryCode && <span className="mr-1">{countryCodeToFlag(countryCode)}</span>}+ {locationLine}+ </MetaItem>+ )}+ {libraryLine && <MetaItem icon={<IconCode />}>{libraryLine}</MetaItem>}+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsxindex 92acc4c13380..9ab401776b67 100644--- a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx+++ b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx@@ -68,6 +68,7 @@ import { SurveyResultsRefreshStatus } from '../components/SurveyResultsRefreshStimport { NEW_SURVEY } from '../constants'import { SurveyDraftContent } from './SurveyDraftContent'import { SurveyResultsFiltersBar } from './SurveyFilters'+import { SurveyResponseExpandedRow } from './SurveyResponseExpandedRow'import { SurveyDetailsPanel, SurveyExportPanel } from './SurveySidebar'const RESOURCE_TYPE = 'survey'@@ -665,15 +666,29 @@ function SurveySummaryContent({ onViewResponses }: { onViewResponses: () => void)}+function getUuidFromExpandableRecord(record: { result?: unknown }): string | undefined {+ const result = record?.result+ if (!Array.isArray(result)) {+ return undefined+ }+ const event = result[0] as { uuid?: string } | undefined+ return event?.uuid+}++// Don't trigger row expansion when the click originated from an interactive element inside the row.+const INTERACTIVE_SELECTOR = 'a, button, input, select, textarea, [role="button"], [data-skip-row-expand]'+function SurveyResponsesContent(): JSX.Element {const {dataTableQuery,survey,surveyLoading,archivedResponseUuids,+ expandedResponseUuids,isAnyResultsLoading,resultsRequeryInProgress,} = useValues(surveyLogic)+ const { setResponseExpanded, toggleResponseExpansion } = useActions(surveyLogic)const isInitialSurveyLoad = surveyLoading && survey.id === NEW_SURVEY.idconst isRefreshingResults = resultsRequeryInProgress || isAnyResultsLoadingconst surveyColumnRenderers = useSurveyResponseColumns()@@ -702,17 +717,46 @@ function SurveyResponsesContent(): JSX.Element {if (typeof record !== 'object' || !record || !('result' in record)) {return {}}- const result = record.result+ const result = (record as { result?: unknown }).resultif (!Array.isArray(result)) {return {}}+ const uuid = (result[0] as { uuid?: string } | undefined)?.uuid+ const isArchived = uuid ? archivedResponseUuids.has(uuid) : falsereturn {- className:- result[0]?.uuid && archivedResponseUuids.has(result[0].uuid)- ? 'opacity-50'- : undefined,+ className: `cursor-pointer ${isArchived ? 'opacity-50' : ''}`.trim(),+ onClick: (e: React.MouseEvent<HTMLTableRowElement>) => {+ if (!uuid) {+ return+ }+ if ((e.target as HTMLElement).closest(INTERACTIVE_SELECTOR)) {+ return+ }+ toggleResponseExpansion(uuid)+ },}},+ expandable: {+ expandedRowRender: ({ result }) => <SurveyResponseExpandedRow result={result} />,+ rowExpandable: ({ result }) => !!result,+ isRowExpanded: (record) => {+ const uuid = getUuidFromExpandableRecord(record)+ return uuid ? expandedResponseUuids.has(uuid) : false+ },+ onRowExpand: (record) => {+ const uuid = getUuidFromExpandableRecord(record)+ if (uuid) {+ setResponseExpanded(uuid, true)+ }+ },+ onRowCollapse: (record) => {+ const uuid = getUuidFromExpandableRecord(record)+ if (uuid) {+ setResponseExpanded(uuid, false)+ }+ },+ noIndent: true,+ },}}/></div>diff --git a/frontend/src/scenes/surveys/hooks/useSurveyResponseColumns.tsx b/frontend/src/scenes/surveys/hooks/useSurveyResponseColumns.tsxindex 9541db5c6877..f3f8479d1e59 100644--- a/frontend/src/scenes/surveys/hooks/useSurveyResponseColumns.tsx+++ b/frontend/src/scenes/surveys/hooks/useSurveyResponseColumns.tsx@@ -5,10 +5,11 @@ import { IconLlmAnalytics, IconThumbsDown, IconThumbsUp } from '@posthog/icons'import { LemonButton, Tooltip } from '@posthog/lemon-ui'import { surveyLogic } from 'scenes/surveys/surveyLogic'-import { getSurveyResponse, isThumbQuestion } from 'scenes/surveys/utils'+import { getSurveyResponse, isScaleTwoRating } from 'scenes/surveys/utils'import { urls } from 'scenes/urls'import { QueryContextColumn } from '~/queries/types'+import { SurveyQuestionType } from '~/types'const getTraceIdFromRecord = (record: unknown): string | null => {if (!Array.isArray(record)) {@@ -30,6 +31,7 @@ export const getThumbIcon = (value: unknown): JSX.Element | null => {/*** Custom column renderers for the survey responses data table:+ * - Clamp long answers to 2 lines (full content available via row expansion).* - On the first question, surface a "View LLM trace" button when `$ai_trace_id` is present.* - On thumb questions, render the icon + "Thumbs up/down" instead of the raw `1`/`2` value.*/@@ -40,40 +42,49 @@ export function useSurveyResponseColumns(): Record<string, QueryContextColumn> {const columns: Record<string, QueryContextColumn> = {}survey.questions.forEach((question, index) => {- const isThumb = isThumbQuestion(question)+ const isThumb = isScaleTwoRating(question)const isFirstQuestion = index === 0+ const baseExpression = getSurveyResponse(question, index)+ // Must match the column expression built in surveyLogic.tsx so multi-choice+ // questions (wrapped in arrayStringConcat) also get matched.+ const columnName =+ question.type === SurveyQuestionType.MultipleChoice+ ? `arrayStringConcat(${baseExpression}, ', ')`+ : baseExpression- if (!isThumb && !isFirstQuestion) {- return- }-- const columnName = getSurveyResponse(question, index)columns[columnName] = {render: ({ value, record }) => {const traceId = isFirstQuestion ? getTraceIdFromRecord(record) : null+ const stringValue = value == null ? '' : String(value)- return (- <span className="flex items-center gap-2">- {traceId && (- <Tooltip title="View LLM trace">- <LemonButton- size="xsmall"- icon={- <IconLlmAnalytics className="text-[var(--color-product-llm-analytics-light)]" />- }- to={urls.llmAnalyticsTrace(traceId)}- />- </Tooltip>- )}+ let displayContent: JSX.Element+ if (isThumb && (value == '1' || value == '2')) {+ displayContent = (+ <span className="flex items-center gap-1">+ {getThumbIcon(value)}+ Thumbs {value == '1' ? 'up' : 'down'}+ </span>+ )+ } else {+ displayContent = <span className="whitespace-pre-wrap line-clamp-2">{stringValue}</span>+ }- {isThumb && (value == '1' || value == '2') ? (- <span className="flex items-center gap-1">- {getThumbIcon(value)}- Thumbs {value == '1' ? 'up' : 'down'}- </span>- ) : (- String(value ?? '')- )}+ if (!traceId) {+ return displayContent+ }++ return (+ <span className="flex items-start gap-2 min-w-0">+ <Tooltip title="View LLM trace">+ <LemonButton+ size="xsmall"+ icon={+ <IconLlmAnalytics className="text-[var(--color-product-llm-analytics-light)]" />+ }+ to={urls.llmAnalyticsTrace(traceId)}+ />+ </Tooltip>+ <span className="min-w-0 flex-1">{displayContent}</span></span>)},diff --git a/frontend/src/scenes/surveys/surveyLogic.tsx b/frontend/src/scenes/surveys/surveyLogic.tsxindex bce5de169148..0130ac21bb1f 100644--- a/frontend/src/scenes/surveys/surveyLogic.tsx+++ b/frontend/src/scenes/surveys/surveyLogic.tsx@@ -692,6 +692,8 @@ export const surveyLogic = kea<surveyLogicType>([setInterval: (interval: IntervalType) => ({ interval }),setCompareFilter: (compareFilter: CompareFilter) => ({ compareFilter }),setFilterSurveyStatsByDistinctId: (filterByDistinctId: boolean) => ({ filterByDistinctId }),+ setResponseExpanded: (uuid: string, expanded: boolean) => ({ uuid, expanded }),+ toggleResponseExpansion: (uuid: string) => ({ uuid }),setBaseStatsResults: (results: SurveyBaseStatsResult) => ({ results }),setDismissedAndSentCount: (count: DismissedAndSentCountResult) => ({ count }),setShowArchivedResponses: (show: boolean) => ({ show }),@@ -1521,6 +1523,32 @@ export const surveyLogic = kea<surveyLogicType>([setPersonNames: (state, { personNames }) => ({ ...state, ...personNames }),},],+ expandedResponseUuids: [+ new Set<string>(),+ {+ setResponseExpanded: (state, { uuid, expanded }) => {+ if (expanded === state.has(uuid)) {+ return state+ }+ const next = new Set(state)+ if (expanded) {+ next.add(uuid)+ } else {+ next.delete(uuid)+ }+ return next+ },+ toggleResponseExpansion: (state, { uuid }) => {+ const next = new Set(state)+ if (next.has(uuid)) {+ next.delete(uuid)+ } else {+ next.add(uuid)+ }+ return next+ },+ },+ ],editingLanguage: [null as string | null,{@@ -2193,9 +2221,6 @@ export const surveyLogic = kea<surveyLogicType>([}),'timestamp','person',- `coalesce(JSONExtractString(properties, '$lib_version')) -- Library Version`,- `coalesce(JSONExtractString(properties, '$lib')) -- Library`,- `coalesce(JSONExtractString(properties, '$current_url')) -- URL`,]return {@@ -2221,7 +2246,7 @@ export const surveyLogic = kea<surveyLogicType>([propertiesViaUrl: true,showExport: true,showReload: true,- showRecordingColumn: true,+ showRecordingColumn: false,showEventFilter: false,showPropertyFilter: false,showTimings: false,diff --git a/frontend/src/scenes/surveys/utils.ts b/frontend/src/scenes/surveys/utils.tsindex 183eb4a6ea65..f2ef8979f19d 100644--- a/frontend/src/scenes/surveys/utils.ts+++ b/frontend/src/scenes/surveys/utils.ts@@ -947,6 +947,14 @@ export const isThumbQuestion = (question: SurveyQuestion): boolean => {)}+/**+ * A 2-point rating question always represents a binary thumbs up / thumbs down regardless of `display`,+ * so we render the icon + label in response views to make the value readable at a glance.+ */+export const isScaleTwoRating = (question: SurveyQuestion): boolean => {+ return question.type === SurveyQuestionType.Rating && question.scale === SURVEY_RATING_SCALE.THUMB_2_POINT+}+/*** Splits text pasted into a choice input on newlines or tabs (spreadsheet rows).* Returns the merged choices array, or `null` if there's nothing to split (the caller