: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): add intro screen editor panel, preview, and translations (#116325)
Lucas Fariafef465bf8ade
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex efdaf5f905d2..2dd9c06c122f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -14461,7 +14461,7 @@ snapshots:scenes-app-surveys--new-multi-question-survey-section--dark:hash: v1.k794b7964.f1587352973fbb7df0437cfdbfbaa542471fc17044e083be0e4efad7647bbbfe.RMYkIsFv05--LXj0yuYuDLg5-_bX6Ucy9iUMuY6kaYwscenes-app-surveys--new-multi-question-survey-section--light:- hash: v1.k794b7964.ad5861ea909368188bb3fec2edfddf542bfb31230e9bdcdbd7f993ea42885d23.Ych93ianW7eWaE-_7KUOaJTKhoW4jS34LwLcqIP0ncA+ hash: v1.k794b7964.71f2fb743d24041a4cc4bb4b30fb7108bd4f6511f0982aa91c6b9c8809c59913.6fOUDLbMMAlQP91-m44tzRQ6u7EaJgkH9qHF7nSF5P0scenes-app-surveys--new-survey--dark:hash: v1.k794b7964.743d7e70837c5888369cfee589f3f0eec882ecdf6432afed3f4f9f7d232c01df.QPoGwmId8jidosxDszIf3KWG547h_uoj60OZ4OYYl4gscenes-app-surveys--new-survey--light:diff --git a/frontend/src/scenes/surveys/HostedSurveyEdit.tsx b/frontend/src/scenes/surveys/HostedSurveyEdit.tsxindex 4c94ed803604..ba0a8262ec1e 100644--- a/frontend/src/scenes/surveys/HostedSurveyEdit.tsx+++ b/frontend/src/scenes/surveys/HostedSurveyEdit.tsx@@ -422,7 +422,7 @@ export function HostedSurveyEdit({ id }: { id: string }): JSX.Element {[survey, activeLanguage])const maxPageIndex = Math.max(survey.questions.length + (survey.appearance?.displayThankYouMessage ? 1 : 0) - 1, 0)- const activePageIndex = Math.min(selectedPageIndex ?? 0, maxPageIndex)+ const activePageIndex = Math.min(Math.max(selectedPageIndex ?? 0, 0), maxPageIndex)const isConfirmationSelected =!!survey.appearance?.displayThankYouMessage && activePageIndex === survey.questions.lengthconst hostedSurveyUrl = id === 'new' ? null : getHostedSurveyUrl(id)diff --git a/frontend/src/scenes/surveys/SurveyEdit.tsx b/frontend/src/scenes/surveys/SurveyEdit.tsxindex 932dd63e7caa..6b59c3768c43 100644--- a/frontend/src/scenes/surveys/SurveyEdit.tsx+++ b/frontend/src/scenes/surveys/SurveyEdit.tsx@@ -67,16 +67,23 @@ import {import { SurveyBranchingFlowModal } from './branching-flow/SurveyBranchingFlowModal'import { SurveyPublicContentNotice } from './components/SurveyPublicContentNotice'import { SurveyUrlAudienceEstimate } from './components/SurveyUrlAudienceEstimate'-import { SURVEY_TYPE_LABEL_MAP, SurveyMatchTypeLabels, defaultSurveyFieldValues } from './constants'+import {+ INTRO_SCREEN_PAGE_INDEX,+ SURVEY_TYPE_LABEL_MAP,+ SurveyMatchTypeLabels,+ defaultSurveyFieldValues,+} from './constants'import { COMMON_LANGUAGES, getBaseLanguage, getSurveyLanguageName } from './language'import { SurveyAPIEditor } from './SurveyAPIEditor'import { SurveyAppearancePreview } from './SurveyAppearancePreview'import { HTMLEditor, PresentationTypeCard } from './SurveyAppearanceUtils'+import { SurveyEditIntroScreenContent } from './SurveyEditIntroScreenContent'+import { SurveyEditIntroScreenHeader } from './SurveyEditIntroScreenHeader'import { SurveyEditQuestionGroup, SurveyEditQuestionHeader } from './SurveyEditQuestionRow'import { SurveyFormAppearance } from './SurveyFormAppearance'import { DataCollectionType, SurveyEditSection, surveyLogic } from './surveyLogic'import { surveysLogic } from './surveysLogic'-import { canUseSurveyWizard } from './utils'+import { canUseSurveyWizard, withIntroScreenEnabled } from './utils'function SurveyCompletionConditions(): JSX.Element {const { survey, dataCollectionType, isAdaptiveLimitFFEnabled } = useValues(surveyLogic)@@ -244,6 +251,9 @@ function formatFieldName(field: string): string {thankYouMessageHeader: 'Thank you message header',thankYouMessageDescription: 'Thank you message description',thankYouMessageCloseButtonText: 'Thank you close button text',+ introScreenHeader: 'Intro screen header',+ introScreenDescription: 'Intro screen description',+ introScreenButtonText: 'Intro screen button text',question: 'Question text',buttonText: 'Button text',lowerBoundLabel: 'Lower bound label',@@ -789,6 +799,22 @@ export default function SurveyEdit({ id }: { id: string }): JSX.Element {setSelectedPageIndex(index)}}panels={[+ ...(survey.appearance?.displayIntroScreen+ ? [+ {+ key: INTRO_SCREEN_PAGE_INDEX,+ dataAttr: 'survey-intro-screen-panel',+ header: <SurveyEditIntroScreenHeader />,+ content: (+ <SurveyEditIntroScreenContent+ activeEditingLanguage={+ activeEditingLanguage+ }+ />+ ),+ },+ ]+ : []),...survey.questions.map((question:@@ -1290,6 +1316,23 @@ export default function SurveyEdit({ id }: { id: string }): JSX.Element {</LemonButton>)}</div>+ {!survey.appearance?.displayIntroScreen && (+ <LemonButton+ type="secondary"+ className="w-max mt-2"+ icon={<IconPlus />}+ data-attr="add-intro-screen"+ onClick={() => {+ setSurveyValue(+ 'appearance',+ withIntroScreenEnabled(survey.appearance)+ )+ setSelectedPageIndex(INTRO_SCREEN_PAGE_INDEX)+ }}+ >+ Add intro screen+ </LemonButton>+ )}{!survey.appearance?.displayThankYouMessage && (<LemonButtontype="secondary"diff --git a/frontend/src/scenes/surveys/SurveyEditIntroScreenContent.tsx b/frontend/src/scenes/surveys/SurveyEditIntroScreenContent.tsxnew file mode 100644index 000000000000..93c860add08c--- /dev/null+++ b/frontend/src/scenes/surveys/SurveyEditIntroScreenContent.tsx@@ -0,0 +1,137 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonInput, LemonTag, Tooltip } from '@posthog/lemon-ui'++import { LemonField } from 'lib/lemon-ui/LemonField'++import { INTRO_SCREEN_DEFAULT_BUTTON_TEXT, INTRO_SCREEN_TEXT_FIELDS } from './constants'+import { HTMLEditor } from './SurveyAppearanceUtils'+import { getIntroScreenDescriptionContentType, isIntroScreenShown } from './surveyIntroScreen'+import { surveyLogic } from './surveyLogic'++type IntroScreenTextField = (typeof INTRO_SCREEN_TEXT_FIELDS)[number]++type IntroScreenInputProps = {+ value: string+ onChange: (value: string) => void+ placeholder: string+ className: string+}++const PLACEHOLDERS: Record<IntroScreenTextField, string> = {+ introScreenHeader: 'ex: Help us improve',+ introScreenDescription: 'ex: This takes less than a minute.',+ introScreenButtonText: INTRO_SCREEN_DEFAULT_BUTTON_TEXT,+}++export function SurveyEditIntroScreenContent({+ activeEditingLanguage,+}: {+ activeEditingLanguage: string | null+}): JSX.Element {+ const { survey, translationErrorsForField, aiGeneratedTranslationFields } = useValues(surveyLogic)+ const { setSurveyValue, clearAiGeneratedTranslationField } = useActions(surveyLogic)++ const isAiGenerated = (field: IntroScreenTextField): boolean =>+ !!activeEditingLanguage &&+ aiGeneratedTranslationFields.includes(`translations.${activeEditingLanguage}.${field}`)++ const setValue = (field: IntroScreenTextField, value: string): void => {+ if (activeEditingLanguage) {+ clearAiGeneratedTranslationField(`translations.${activeEditingLanguage}.${field}`)+ setSurveyValue('translations', {+ ...survey.translations,+ [activeEditingLanguage]: { ...survey.translations?.[activeEditingLanguage], [field]: value },+ })+ } else {+ setSurveyValue('appearance', { ...survey.appearance, [field]: value })+ }+ }++ const renderField = (+ field: IntroScreenTextField,+ label: string,+ renderInput: (props: IntroScreenInputProps) => JSX.Element,+ className?: string+ ): JSX.Element => {+ const error = translationErrorsForField(-1, field)+ return (+ <LemonField.Pure+ label={+ isAiGenerated(field) ? (+ <span className="flex items-center gap-1">+ <span>{label}</span>+ <LemonTag type="highlight">AI draft</LemonTag>+ </span>+ ) : (+ label+ )+ }+ className={className}+ >+ <Tooltip title={error?.error ?? ''} placement="top">+ {renderInput({+ value:+ (activeEditingLanguage+ ? survey.translations?.[activeEditingLanguage]?.[field]+ : survey.appearance?.[field]) ?? '',+ onChange: (value) => setValue(field, value),+ placeholder: activeEditingLanguage ? (survey.appearance?.[field] ?? '') : PLACEHOLDERS[field],+ className: [+ error ? 'border border-warning hover:border-primary' : '',+ isAiGenerated(field)+ ? 'border border-dashed border-accent bg-accent-highlight-secondary'+ : '',+ ]+ .filter(Boolean)+ .join(' '),+ })}+ </Tooltip>+ </LemonField.Pure>+ )+ }++ return (+ <>+ {!isIntroScreenShown(survey.appearance) && (+ <LemonBanner type="warning" className="mb-2">+ The intro screen won't show until it has a header or a description.+ </LemonBanner>+ )}+ <p className="text-secondary text-xs mb-2">+ The survey counts as shown while the intro is on screen, so response rates include people who never+ start the questions.+ </p>+ {renderField('introScreenHeader', 'Intro header', (props) => (+ <LemonInput {...props} />+ ))}+ {renderField(+ 'introScreenDescription',+ 'Intro description',+ ({ placeholder, ...props }) => (+ <HTMLEditor+ {...props}+ textPlaceholder={placeholder}+ activeTab={getIntroScreenDescriptionContentType(survey.appearance)}+ onTabChange={(key) =>+ setSurveyValue('appearance', {+ ...survey.appearance,+ introScreenDescriptionContentType: key === 'html' ? 'html' : 'text',+ })+ }+ disableTabSwitching={!!activeEditingLanguage}+ />+ ),+ 'mt-3'+ )}+ {renderField(+ 'introScreenButtonText',+ 'Button text',+ (props) => (+ <LemonInput {...props} />+ ),+ 'mt-2'+ )}+ </>+ )+}diff --git a/frontend/src/scenes/surveys/SurveyEditIntroScreenHeader.tsx b/frontend/src/scenes/surveys/SurveyEditIntroScreenHeader.tsxnew file mode 100644index 000000000000..b83216c11019--- /dev/null+++ b/frontend/src/scenes/surveys/SurveyEditIntroScreenHeader.tsx@@ -0,0 +1,38 @@+import { useActions, useValues } from 'kea'++import { IconTrash, IconWarning } from '@posthog/icons'+import { LemonButton, Tooltip } from '@posthog/lemon-ui'++import { INTRO_SCREEN_TEXT_FIELDS } from './constants'+import { surveyLogic } from './surveyLogic'++export function SurveyEditIntroScreenHeader(): JSX.Element {+ const { survey, translationErrorsForField } = useValues(surveyLogic)+ const { setSurveyValue, setSelectedPageIndex } = useActions(surveyLogic)++ const errorCount = INTRO_SCREEN_TEXT_FIELDS.filter((field) => translationErrorsForField(-1, field)).length++ return (+ <div className="flex flex-row w-full items-center justify-between">+ <b>Intro screen</b>+ <div className="flex items-center gap-1">+ {errorCount > 0 && (+ <Tooltip title={`${errorCount} translation validation issue${errorCount > 1 ? 's' : ''}`}>+ <IconWarning className="text-warning" />+ </Tooltip>+ )}+ <LemonButton+ icon={<IconTrash />}+ data-attr="delete-survey-intro-screen"+ size="xsmall"+ onClick={(e) => {+ e.stopPropagation()+ setSelectedPageIndex(0)+ setSurveyValue('appearance', { ...survey.appearance, displayIntroScreen: false })+ }}+ tooltipPlacement="top-end"+ />+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/surveys/SurveyFormAppearance.tsx b/frontend/src/scenes/surveys/SurveyFormAppearance.tsxindex ade0c7796e86..614c47f87016 100644--- a/frontend/src/scenes/surveys/SurveyFormAppearance.tsx+++ b/frontend/src/scenes/surveys/SurveyFormAppearance.tsx@@ -1,16 +1,17 @@import { useValues } from 'kea'-import { getNextSurveyStep } from 'posthog-js/dist/surveys-preview'import { LemonSelect } from '@posthog/lemon-ui'import { LemonField } from 'lib/lemon-ui/LemonField'import { surveysLogic } from 'scenes/surveys/surveysLogic'-import { Survey, SurveyQuestionBranchingType, SurveyType } from '~/types'+import { Survey, SurveyType } from '~/types'-import { NewSurvey } from './constants'+import { INTRO_SCREEN_PAGE_INDEX, NewSurvey } from './constants'import { SurveyAPIEditor } from './SurveyAPIEditor'import { SurveyAppearancePreview } from './SurveyAppearancePreview'+import { getNextPreviewPageIndex } from './surveyPreviewNavigation'+import { clampPreviewPageIndex, getIntroScreenPageOptions } from './utils'interface SurveyFormAppearanceProps {previewPageIndex: number@@ -25,6 +26,7 @@ export function SurveyFormAppearance({handleSetSelectedPageIndex,}: SurveyFormAppearanceProps): JSX.Element | null {const { isAppearanceModalOpen } = useValues(surveysLogic)+ const effectivePageIndex = clampPreviewPageIndex(previewPageIndex, survey)if (isAppearanceModalOpen) {return null@@ -34,17 +36,21 @@ export function SurveyFormAppearance({<div className="flex flex-col h-full gap-2 items-start flex-1 xl:pl-8 pt-8 xl:pt-0"><SurveyAppearancePreviewsurvey={survey as Survey}- previewPageIndex={previewPageIndex}+ previewPageIndex={effectivePageIndex}onPreviewSubmit={(response) => {- const nextStep = getNextSurveyStep(survey, previewPageIndex, response)- if (nextStep === SurveyQuestionBranchingType.End && !survey.appearance?.displayThankYouMessage) {- return+ const nextPageIndex = getNextPreviewPageIndex(survey, effectivePageIndex, response)+ if (nextPageIndex !== null) {+ handleSetSelectedPageIndex(nextPageIndex)}+ }}+ onPreviewBack={() =>handleSetSelectedPageIndex(- nextStep === SurveyQuestionBranchingType.End ? survey.questions.length : nextStep+ Math.max(+ survey.appearance?.displayIntroScreen ? INTRO_SCREEN_PAGE_INDEX : 0,+ effectivePageIndex - 1+ ))- }}- onPreviewBack={() => handleSetSelectedPageIndex(Math.max(0, previewPageIndex - 1))}+ }/><LemonField.Pure label="Current question" className="max-w-xs gap-1" htmlFor="current-question-select"><LemonSelect@@ -52,8 +58,9 @@ export function SurveyFormAppearance({id="current-question-select"fullWidthtruncateText={{ maxWidthClass: 'max-w-60' }}- value={previewPageIndex}+ value={effectivePageIndex}options={[+ ...getIntroScreenPageOptions(survey),...survey.questions.map((question, index) => ({label: `${index + 1}. ${question.question ?? ''}`,value: index,diff --git a/frontend/src/scenes/surveys/SurveyTranslationFields.tsx b/frontend/src/scenes/surveys/SurveyTranslationFields.tsxindex e0b757f85806..71648588c930 100644--- a/frontend/src/scenes/surveys/SurveyTranslationFields.tsx+++ b/frontend/src/scenes/surveys/SurveyTranslationFields.tsx@@ -6,7 +6,7 @@ import { LemonField } from 'lib/lemon-ui/LemonField'import { SurveyQuestion } from '~/types'-import { defaultSurveyAppearance } from './constants'+import { defaultSurveyAppearance, INTRO_SCREEN_DEFAULT_BUTTON_TEXT } from './constants'import { isChoiceQuestion, isLinkQuestion, isRatingQuestion } from './questionTypeGuards'import { surveyLogic } from './surveyLogic'@@ -132,6 +132,36 @@ export function SurveyTranslationFields({ activeLanguage }: { activeLanguage: streturn (<div className="space-y-6">+ {appearance.displayIntroScreen ? (+ <section className="space-y-3">+ <h4 className="m-0 text-xs font-semibold uppercase tracking-wide text-muted">Intro screen</h4>+ <GuidedTranslationInput+ label="Header"+ value={translations[activeLanguage]?.introScreenHeader || ''}+ source={appearance.introScreenHeader}+ aiGenerated={isGeneratedSurveyField('introScreenHeader')}+ onChange={(introScreenHeader) => updateSurveyTranslation({ introScreenHeader })}+ />+ {appearance.introScreenDescription ? (+ <GuidedTranslationInput+ label="Description"+ value={translations[activeLanguage]?.introScreenDescription || ''}+ source={appearance.introScreenDescription}+ aiGenerated={isGeneratedSurveyField('introScreenDescription')}+ onChange={(introScreenDescription) => updateSurveyTranslation({ introScreenDescription })}+ multiline+ />+ ) : null}+ <GuidedTranslationInput+ label="Button text"+ value={translations[activeLanguage]?.introScreenButtonText || ''}+ source={appearance.introScreenButtonText || INTRO_SCREEN_DEFAULT_BUTTON_TEXT}+ aiGenerated={isGeneratedSurveyField('introScreenButtonText')}+ onChange={(introScreenButtonText) => updateSurveyTranslation({ introScreenButtonText })}+ />+ </section>+ ) : null}+{survey.questions.map((question, questionIndex) => {const questionTranslation = question.translations?.[activeLanguage] ?? {}const ratingQuestion = isRatingQuestion(question) ? question : nulldiff --git a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveySidebar.tsx b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveySidebar.tsxindex 3452e38ce17a..d32024537325 100644--- a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveySidebar.tsx+++ b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveySidebar.tsx@@ -1,5 +1,4 @@import { useActions, useValues } from 'kea'-import { getNextSurveyStep } from 'posthog-js/dist/surveys-preview'import { ReactNode } from 'react'import { IconDownload } from '@posthog/icons'@@ -13,7 +12,10 @@ import { pluralize } from 'lib/utils/strings'import { SURVEY_TYPE_LABEL_MAP } from 'scenes/surveys/constants'import { SurveyAppearancePreview } from 'scenes/surveys/SurveyAppearancePreview'import { surveyLogic } from 'scenes/surveys/surveyLogic'+import { getNextPreviewPageIndex } from 'scenes/surveys/surveyPreviewNavigation'import {+ clampPreviewPageIndex,+ getIntroScreenPageOptions,getRecurringSurveyScheduleInfo,getSurveyCollectionLimitSummary,getSurveyDisplayConditionsSummary,@@ -24,7 +26,6 @@ import {AccessControlResourceType,ExporterFormat,Survey,- SurveyQuestionBranchingType,SurveySchedule as SurveyScheduleEnum,SurveyType,} from '~/types'@@ -83,6 +84,7 @@ export function SurveyDetailsPanel(): JSX.Element {const conditionsSummary = hasTargetingSet ? getSurveyDisplayConditionsSummary(survey as Survey) : []const collectionLimitSummary = getSurveyCollectionLimitSummary(survey)const scheduleInfo = getRecurringSurveyScheduleInfo(survey)+ const effectivePageIndex = clampPreviewPageIndex(selectedPageIndex, survey)return (<div className="flex flex-col gap-6">@@ -93,29 +95,22 @@ export function SurveyDetailsPanel(): JSX.Element {<div className="flex justify-center"><SurveyAppearancePreviewsurvey={survey as Survey}- previewPageIndex={selectedPageIndex || 0}+ previewPageIndex={effectivePageIndex}onPreviewSubmit={(response) => {- const nextStep = getNextSurveyStep(survey, selectedPageIndex, response)- if (- nextStep === SurveyQuestionBranchingType.End &&- !survey.appearance?.displayThankYouMessage- ) {- return+ const nextPageIndex = getNextPreviewPageIndex(survey, effectivePageIndex, response)+ if (nextPageIndex !== null) {+ setSelectedPageIndex(nextPageIndex)}- setSelectedPageIndex(- nextStep === SurveyQuestionBranchingType.End- ? survey.questions.length- : nextStep- )}}/></div><LemonSelectsize="xsmall"fullWidth- value={selectedPageIndex || 0}+ value={effectivePageIndex}onChange={(pageIndex) => setSelectedPageIndex(pageIndex)}options={[+ ...getIntroScreenPageOptions(survey),...survey.questions.map((question, index) => ({label: `${index + 1}. ${question.question ?? ''}`,value: index,diff --git a/frontend/src/scenes/surveys/constants.tsx b/frontend/src/scenes/surveys/constants.tsxindex 438088fe32cd..c93e1ded31b8 100644--- a/frontend/src/scenes/surveys/constants.tsx+++ b/frontend/src/scenes/surveys/constants.tsx@@ -59,6 +59,14 @@ export type SurveyRatingScaleValue = (typeof SURVEY_RATING_SCALE)[keyof typeof S// Leading page sentinel: the confirmation message trails at questions.length, so the intro sits at -1 and question indices never shift.export const INTRO_SCREEN_PAGE_INDEX = -1+export const INTRO_SCREEN_TEXT_FIELDS = [+ 'introScreenHeader',+ 'introScreenDescription',+ 'introScreenButtonText',+] as const++export const INTRO_SCREEN_DEFAULT_BUTTON_TEXT = 'Get started'+// Create SurveyMatchTypeLabels using allOperatorsMappingexport const SurveyMatchTypeLabels = {[SurveyMatchType.Exact]: allOperatorsMapping[SurveyMatchType.Exact],diff --git a/frontend/src/scenes/surveys/survey-appearance/SurveyAppearanceModal.tsx b/frontend/src/scenes/surveys/survey-appearance/SurveyAppearanceModal.tsxindex 15a81e14d913..0d4fd0d20109 100644--- a/frontend/src/scenes/surveys/survey-appearance/SurveyAppearanceModal.tsx+++ b/frontend/src/scenes/surveys/survey-appearance/SurveyAppearanceModal.tsx@@ -1,6 +1,5 @@import clsx from 'clsx'import { useActions, useValues } from 'kea'-import { getNextSurveyStep } from 'posthog-js/dist/surveys-preview'import { useState } from 'react'import { IconGear } from '@posthog/icons'@@ -15,10 +14,12 @@ import {} from 'scenes/surveys/survey-appearance/SurveyAppearanceSections'import { CommonProps } from 'scenes/surveys/survey-appearance/types'-import { AvailableFeature, SurveyQuestionBranchingType, SurveyType } from '~/types'+import { AvailableFeature, SurveyType } from '~/types'import { SurveyAppearancePreview } from '../SurveyAppearancePreview'+import { getNextPreviewPageIndex } from '../surveyPreviewNavigation'import { surveysLogic } from '../surveysLogic'+import { clampPreviewPageIndex, getIntroScreenPageOptions } from '../utils'type PreviewScreenSize = 'mobile' | 'tablet' | 'desktop'@@ -37,6 +38,7 @@ function SurveyPreview({const [surveyPreviewBackground, setSurveyPreviewBackground] = useState<'light' | 'dark'>('light')const currentDimensions = screenDimensions[activeScreenSize]+ const effectivePageIndex = clampPreviewPageIndex(selectedPageIndex, survey)return (<div className="flex flex-[1.5] flex-col items-center justify-start rounded overflow-hidden gap-2"><LemonTabs@@ -59,9 +61,10 @@ function SurveyPreview({<LemonSelectonChange={(pageIndex) => setSelectedPageIndex(pageIndex)}className="whitespace-nowrap max-w-fit"- value={selectedPageIndex || 0}+ value={effectivePageIndex}id="survey-preview-question-select"options={[+ ...getIntroScreenPageOptions(survey),...survey.questions.map((question, index) => ({label: `${index + 1}. ${question.question || 'Untitled Question'}`,value: index,@@ -100,21 +103,15 @@ function SurveyPreview({><SurveyAppearancePreviewsurvey={survey}- previewPageIndex={selectedPageIndex || 0}+ previewPageIndex={effectivePageIndex}positionStyles={{position: 'absolute',}}onPreviewSubmit={(response) => {- const nextStep = getNextSurveyStep(survey, selectedPageIndex, response)- if (- nextStep === SurveyQuestionBranchingType.End &&- !survey.appearance?.displayThankYouMessage- ) {- return+ const nextPageIndex = getNextPreviewPageIndex(survey, effectivePageIndex, response)+ if (nextPageIndex !== null) {+ setSelectedPageIndex?.(nextPageIndex)}- setSelectedPageIndex?.(- nextStep === SurveyQuestionBranchingType.End ? survey.questions.length : nextStep- )}}/></div>diff --git a/frontend/src/scenes/surveys/surveyLogic.test.ts b/frontend/src/scenes/surveys/surveyLogic.test.tsindex 633d9952781f..e6a30122f9cb 100644--- a/frontend/src/scenes/surveys/surveyLogic.test.ts+++ b/frontend/src/scenes/surveys/surveyLogic.test.ts@@ -5,6 +5,7 @@ import api from 'lib/api'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { dayjs } from 'lib/dayjs'import {+ getSurveyTranslationDraftPayload,mergeResponsesByQuestion,processOpenEndedResults,processResultsForSurveyQuestions,@@ -250,6 +251,80 @@ describe('translation validation', () => {})})+ it.each(['introScreenHeader', 'introScreenDescription', 'introScreenButtonText'] as const)(+ 'validates the %s translation like the confirmation message',+ async (field) => {+ const survey = {+ ...createPersistedSurvey(),+ appearance: { displayIntroScreen: true, [field]: 'Welcome' },+ translations: { fr: { [field]: '[Translation needed]' } },+ } as Survey++ await expectLogic(logic, () => {+ logic.actions.loadSurveySuccess(survey)+ }).toMatchValues({+ translationValidationErrors: [+ {+ language: 'fr',+ questionIndex: -1,+ field,+ error: 'Contains placeholder "[Translation needed]"',+ },+ ],+ })+ }+ )++ it.each([+ ['an empty button text', 'introScreenButtonText', '', []],+ ['an unset button text', 'introScreenButtonText', undefined, []],+ [+ 'an empty header',+ 'introScreenHeader',+ '',+ [+ {+ language: 'default',+ questionIndex: -1,+ field: 'introScreenHeader',+ error: 'Cannot be empty (has translation)',+ },+ ],+ ],+ ] as const)('checks a translated intro field against %s', async (_name, field, base, expected) => {+ const survey = {+ ...createPersistedSurvey(),+ appearance: { displayIntroScreen: true, [field]: base },+ translations: { fr: { [field]: 'Commencer' } },+ } as Survey++ await expectLogic(logic, () => {+ logic.actions.loadSurveySuccess(survey)+ }).toMatchValues({ translationValidationErrors: expected })+ })++ it('skips intro translation checks while the intro is off', async () => {+ const survey = {+ ...createPersistedSurvey(),+ appearance: { displayIntroScreen: false, introScreenHeader: 'Welcome' },+ translations: { fr: { introScreenHeader: '[Translation needed]' } },+ } as Survey++ await expectLogic(logic, () => {+ logic.actions.loadSurveySuccess(survey)+ }).toMatchValues({ translationValidationErrors: [] })+ })++ it.each([+ ['an enabled intro with no button text', { displayIntroScreen: true }, 'Get started'],+ ['an enabled intro with button text', { displayIntroScreen: true, introScreenButtonText: 'Go' }, 'Go'],+ ['a disabled intro', { displayIntroScreen: false }, undefined],+ ] as const)('sends the effective intro button text to AI translation for %s', (_name, appearance, expected) => {+ const payload = getSurveyTranslationDraftPayload({ ...createPersistedSurvey(), appearance } as Survey)++ expect(payload.appearance?.introScreenButtonText).toBe(expected)+ })+it('does not validate survey root description translations', async () => {const survey = {...createPersistedSurvey(),diff --git a/frontend/src/scenes/surveys/surveyLogic.tsx b/frontend/src/scenes/surveys/surveyLogic.tsxindex d54a6bceff23..aff010cf6c55 100644--- a/frontend/src/scenes/surveys/surveyLogic.tsx+++ b/frontend/src/scenes/surveys/surveyLogic.tsx@@ -114,6 +114,8 @@ import type {UserType,} from '../../types'import {+ INTRO_SCREEN_DEFAULT_BUTTON_TEXT,+ INTRO_SCREEN_TEXT_FIELDS,LOADING_SURVEY_RESULTS_TOAST_ID,NEW_SURVEY,NewSurvey,@@ -242,7 +244,7 @@ function getTranslationDraftQuestionId(question: SurveyQuestion, index: number):return question.id || `${DRAFT_TRANSLATION_QUESTION_ID_PREFIX}${index}`}-function getSurveyTranslationDraftPayload(survey: Survey | NewSurvey): SurveyTranslationDraftPayload {+export function getSurveyTranslationDraftPayload(survey: Survey | NewSurvey): SurveyTranslationDraftPayload {return {name: survey.name,description: survey.description,@@ -253,7 +255,9 @@ function getSurveyTranslationDraftPayload(survey: Survey | NewSurvey): SurveyTrathankYouMessageCloseButtonText: survey.appearance?.thankYouMessageCloseButtonText,introScreenHeader: survey.appearance?.introScreenHeader,introScreenDescription: survey.appearance?.introScreenDescription,- introScreenButtonText: survey.appearance?.introScreenButtonText,+ introScreenButtonText: survey.appearance?.displayIntroScreen+ ? survey.appearance.introScreenButtonText || INTRO_SCREEN_DEFAULT_BUTTON_TEXT+ : survey.appearance?.introScreenButtonText,},questions: survey.questions.map((question, index): SurveyTranslationDraftQuestion => {const draftQuestion: SurveyTranslationDraftQuestion = {@@ -3426,6 +3430,15 @@ export const surveyLogic = kea<surveyLogicType>([key: 'thankYouMessageCloseButtonText',defaultValue: survey.appearance?.thankYouMessageCloseButtonText,},+ ...(survey.appearance?.displayIntroScreen+ ? INTRO_SCREEN_TEXT_FIELDS.map((key) => ({+ key,+ defaultValue:+ key === 'introScreenButtonText'+ ? survey.appearance?.[key] || INTRO_SCREEN_DEFAULT_BUTTON_TEXT+ : survey.appearance?.[key],+ }))+ : []),]// Get all languagesdiff --git a/frontend/src/scenes/surveys/surveyPreviewNavigation.test.ts b/frontend/src/scenes/surveys/surveyPreviewNavigation.test.tsnew file mode 100644index 000000000000..290ffeca0c20--- /dev/null+++ b/frontend/src/scenes/surveys/surveyPreviewNavigation.test.ts@@ -0,0 +1,33 @@+import { getNextSurveyStep } from 'posthog-js/dist/surveys-preview'++import { Survey, SurveyQuestionBranchingType } from '~/types'++import { getNextPreviewPageIndex } from './surveyPreviewNavigation'++describe('getNextPreviewPageIndex', () => {+ const buildSurvey = (displayThankYouMessage: boolean): Survey =>+ ({ questions: [{}, {}], appearance: { displayThankYouMessage } }) as Survey++ it.each([+ ['advances from the intro to question 0 without consulting branching', -1, true, undefined, 0],+ ['follows the branching result to the next question', 0, true, 1, 1],+ [+ 'goes to the confirmation message when branching ends the survey',+ 1,+ true,+ SurveyQuestionBranchingType.End,+ 2,+ ],+ [+ 'stays put when branching ends the survey and there is no confirmation',+ 1,+ false,+ SurveyQuestionBranchingType.End,+ null,+ ],+ ] as const)('%s', (_name, pageIndex, displayThankYouMessage, nextStep, expected) => {+ jest.mocked(getNextSurveyStep).mockReturnValue(nextStep as any)++ expect(getNextPreviewPageIndex(buildSurvey(displayThankYouMessage), pageIndex, 'answer')).toBe(expected)+ })+})diff --git a/frontend/src/scenes/surveys/surveyPreviewNavigation.ts b/frontend/src/scenes/surveys/surveyPreviewNavigation.tsnew file mode 100644index 000000000000..7aa257b7b9d3--- /dev/null+++ b/frontend/src/scenes/surveys/surveyPreviewNavigation.ts@@ -0,0 +1,22 @@+import { getNextSurveyStep } from 'posthog-js/dist/surveys-preview'++import { Survey, SurveyQuestionBranchingType } from '~/types'++import { INTRO_SCREEN_PAGE_INDEX, NewSurvey } from './constants'++/** The page to show after a preview submit, or null to stay on the current one. */+export function getNextPreviewPageIndex(+ survey: Survey | NewSurvey,+ pageIndex: number,+ response: string | string[] | number | null+): number | null {+ // The intro is not a question, so getNextSurveyStep cannot resolve it.+ if (pageIndex === INTRO_SCREEN_PAGE_INDEX) {+ return 0+ }+ const nextStep = getNextSurveyStep(survey, pageIndex, response)+ if (nextStep !== SurveyQuestionBranchingType.End) {+ return nextStep+ }+ return survey.appearance?.displayThankYouMessage ? survey.questions.length : null+}diff --git a/frontend/src/scenes/surveys/surveyTranslationUtils.test.ts b/frontend/src/scenes/surveys/surveyTranslationUtils.test.tsindex e479e31813f6..915416ea90dc 100644--- a/frontend/src/scenes/surveys/surveyTranslationUtils.test.ts+++ b/frontend/src/scenes/surveys/surveyTranslationUtils.test.ts@@ -116,6 +116,20 @@ describe('getSurveyWithTranslatedContent', () => {expect(translatedSurvey.appearance?.backButtonText).toBe('Retour')})+ it.each(['introScreenHeader', 'introScreenDescription', 'introScreenButtonText'] as const)(+ 'applies the %s translation to the appearance',+ (field) => {+ const survey = createSurvey()+ survey.appearance = { ...survey.appearance, displayIntroScreen: true, [field]: 'Welcome' }+ survey.translations = { fr: { ...survey.translations?.fr, [field]: 'Bienvenue' } }++ const translatedSurvey = getSurveyWithTranslatedContent(survey, 'fr')++ expect(translatedSurvey.appearance?.[field]).toBe('Bienvenue')+ expect(translatedSurvey.appearance?.displayIntroScreen).toBe(true)+ }+ )+it('returns the original survey when the language has no root translation', () => {const survey = createSurvey()diff --git a/frontend/src/scenes/surveys/surveyTranslationUtils.ts b/frontend/src/scenes/surveys/surveyTranslationUtils.tsindex fe6f3cc74c4e..fba86b43ee82 100644--- a/frontend/src/scenes/surveys/surveyTranslationUtils.ts+++ b/frontend/src/scenes/surveys/surveyTranslationUtils.ts@@ -1,6 +1,6 @@import { MultipleSurveyQuestion, Survey, SurveyAppearance, SurveyQuestion, SurveyQuestionType } from '~/types'-import { NewSurvey, TRANSLATION_NEEDED_PLACEHOLDER } from './constants'+import { INTRO_SCREEN_TEXT_FIELDS, NewSurvey, TRANSLATION_NEEDED_PLACEHOLDER } from './constants'// Respondents are shown choices in their own language and submit the translated text, so a// translated choice has to map back to its base-language choice (matched by position) to be@@ -61,6 +61,11 @@ export function getSurveyWithTranslatedContent<TSurvey extends Survey | NewSurveif (translation.thankYouMessageCloseButtonText) {appearanceUpdates.thankYouMessageCloseButtonText = translation.thankYouMessageCloseButtonText}+ for (const field of INTRO_SCREEN_TEXT_FIELDS) {+ if (translation[field]) {+ appearanceUpdates[field] = translation[field]+ }+ }if (translation.submitButtonText) {appearanceUpdates.submitButtonText = translation.submitButtonText}diff --git a/frontend/src/scenes/surveys/useSurveyTranslationsForm.ts b/frontend/src/scenes/surveys/useSurveyTranslationsForm.tsindex 16327a25e0bc..9a9743fdf1a7 100644--- a/frontend/src/scenes/surveys/useSurveyTranslationsForm.ts+++ b/frontend/src/scenes/surveys/useSurveyTranslationsForm.ts@@ -1,6 +1,7 @@import { useActions, useValues } from 'kea'import { useMemo, useState } from 'react'+import { INTRO_SCREEN_DEFAULT_BUTTON_TEXT } from './constants'import {COMMON_LANGUAGES,classifyTranslationKeys,@@ -118,6 +119,9 @@ export function useSurveyTranslationsForm({thankYouMessageHeader: survey.appearance?.thankYouMessageHeader || '',thankYouMessageDescription: survey.appearance?.thankYouMessageDescription || '',thankYouMessageCloseButtonText: survey.appearance?.thankYouMessageCloseButtonText || '',+ introScreenHeader: survey.appearance?.introScreenHeader || '',+ introScreenDescription: survey.appearance?.introScreenDescription || '',+ introScreenButtonText: survey.appearance?.introScreenButtonText || INTRO_SCREEN_DEFAULT_BUTTON_TEXT,},})setEditingLanguage(language)diff --git a/frontend/src/scenes/surveys/utils.test.ts b/frontend/src/scenes/surveys/utils.test.tsindex e9bf23c858a1..e3dbbb72b347 100644--- a/frontend/src/scenes/surveys/utils.test.ts+++ b/frontend/src/scenes/surveys/utils.test.ts@@ -29,6 +29,7 @@ import {calculateNpsBreakdown,createAnswerFilterHogQLExpression,doesSurveyRepeatOnEveryEvent,+ withIntroScreenEnabled,getExpressionCommentForQuestion,getSurveyNotificationFilters,getRecurringSurveyScheduleInfo,@@ -41,6 +42,7 @@ import {getSurveyResponseStatus,transformSurveyResponseRows,getSurveyStartDateForQuery,+ clampPreviewPageIndex,isSimpleSurveyAudienceTargeting,sanitizeColor,sanitizeSurvey,@@ -504,6 +506,18 @@ describe('survey utils', () => {})})+ describe('clampPreviewPageIndex', () => {+ it.each([+ ['keeps the intro page while the intro is enabled', -1, true, -1],+ ['falls back to question 0 when the intro is disabled', -1, false, 0],+ ['keeps question pages regardless of the toggle', 2, false, 2],+ ['maps a null page index to question 0', null, true, 0],+ ] as const)('%s', (_name, pageIndex, displayIntroScreen, expected) => {+ const survey = { appearance: { displayIntroScreen } }+ expect(clampPreviewPageIndex(pageIndex, survey)).toBe(expected)+ })+ })+describe('sanitizeSurveyAppearance', () => {it('returns null for null input', () => {expect(sanitizeSurveyAppearance(null)).toBeNull()@@ -585,6 +599,38 @@ describe('survey utils', () => {})})+ describe('withIntroScreenEnabled', () => {+ it.each([+ ['no appearance', undefined, { displayIntroScreen: true, introScreenDescriptionContentType: 'text' }],+ [+ 'an unset content type',+ { introScreenHeader: 'Welcome' },+ { displayIntroScreen: true, introScreenHeader: 'Welcome', introScreenDescriptionContentType: 'text' },+ ],+ [+ 'an existing html content type',+ { introScreenDescriptionContentType: 'html' },+ { displayIntroScreen: true, introScreenDescriptionContentType: 'html' },+ ],+ [+ 'an existing html description with an unset content type',+ { introScreenDescription: '<b>Hi</b>' },+ {+ displayIntroScreen: true,+ introScreenDescription: '<b>Hi</b>',+ introScreenDescriptionContentType: 'html',+ },+ ],+ [+ 'an existing text description',+ { introScreenDescription: 'Hi', introScreenDescriptionContentType: 'text' },+ { displayIntroScreen: true, introScreenDescription: 'Hi', introScreenDescriptionContentType: 'text' },+ ],+ ] as [string, SurveyAppearance | undefined, SurveyAppearance][])('%s', (_name, appearance, expected) => {+ expect(withIntroScreenEnabled(appearance)).toEqual(expected)+ })+ })+describe('sanitizeSurveyDisplayConditions', () => {it('returns null for null input with non-external survey', () => {expect(sanitizeSurveyDisplayConditions(null, SurveyType.Popover)).toBeNull()diff --git a/frontend/src/scenes/surveys/utils.ts b/frontend/src/scenes/surveys/utils.tsindex 06ca52c11da4..4111984e882d 100644--- a/frontend/src/scenes/surveys/utils.ts+++ b/frontend/src/scenes/surveys/utils.ts@@ -7,6 +7,7 @@ import { dayjs } from 'lib/dayjs'import { dateStringToDayJs } from 'lib/utils/dateFilters'import { getAppContext } from 'lib/utils/getAppContext'import {+ INTRO_SCREEN_PAGE_INDEX,MAX_ITERATION_COUNT,NEW_SURVEY,NewSurvey,@@ -279,6 +280,28 @@ export function sanitizeSurveyDisplayConditions(return sanitized}+/**+ * The renderer shows the intro page for INTRO_SCREEN_PAGE_INDEX in preview mode regardless of+ * `displayIntroScreen` (mirroring how the confirmation page ignores `displayThankYouMessage`),+ * so a page index left on the intro after the toggle turns off must fall back to question 0.+ */+export function clampPreviewPageIndex(+ pageIndex: number | null | undefined,+ survey: Pick<Survey | NewSurvey, 'appearance'>+): number {+ const index = pageIndex ?? 0+ if (index === INTRO_SCREEN_PAGE_INDEX && !survey.appearance?.displayIntroScreen) {+ return 0+ }+ return index+}++export function getIntroScreenPageOptions(+ survey: Pick<Survey | NewSurvey, 'appearance'>+): { label: string; value: number }[] {+ return survey.appearance?.displayIntroScreen ? [{ label: 'Intro screen', value: INTRO_SCREEN_PAGE_INDEX }] : []+}+export function sanitizeSurveyAppearance(appearance?: SurveyAppearance | null,isPartialResponsesEnabled = false,@@ -309,6 +332,17 @@ export function sanitizeSurveyAppearance(}}+// An unset content type means HTML to the SDKs, so a new intro is pinned to the editors' text tab.+// A description that already has content keeps the type it renders with.+export function withIntroScreenEnabled(appearance?: SurveyAppearance | null): SurveyAppearance {+ return {+ ...appearance,+ displayIntroScreen: true,+ introScreenDescriptionContentType:+ appearance?.introScreenDescriptionContentType ?? (appearance?.introScreenDescription ? 'html' : 'text'),+ }+}+export type NPSBreakdown = {total: numberpromoters: number