: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): canvas editor for hosted surveys (click-to-edit preview) (#58926)
Lucas Fariab89cea65934c
diff --git a/frontend/public/surveys/hosted-survey.css b/frontend/public/surveys/hosted-survey.cssindex bb91d4ae8af5..b6c3f960e273 100644--- a/frontend/public/surveys/hosted-survey.css+++ b/frontend/public/surveys/hosted-survey.css@@ -58,7 +58,7 @@ body.PostHogHostedSurvey {}.PostHogHostedSurvey.HostedSurveyPreviewFrame--mobile {- max-width: 360px;+ max-width: 390px;min-height: 560px;padding: 1.25rem;margin: 0 auto;diff --git a/frontend/src/scenes/surveys/HostedSurveyEdit.tsx b/frontend/src/scenes/surveys/HostedSurveyEdit.tsxindex 1484237e488a..744c57e04d09 100644--- a/frontend/src/scenes/surveys/HostedSurveyEdit.tsx+++ b/frontend/src/scenes/surveys/HostedSurveyEdit.tsx@@ -5,10 +5,9 @@ import { SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-import { CSS } from '@dnd-kit/utilities'import { useActions, useValues } from 'kea'import { router } from 'kea-router'-import { getNextSurveyStep } from 'posthog-js/dist/surveys-preview'-import { useMemo, useState, type CSSProperties } from 'react'+import { useMemo, useState } from 'react'-import { IconChevronDown, IconExternal, IconGitBranch, IconPhone, IconTrash, IconWarning } from '@posthog/icons'+import { IconChevronDown, IconExternal, IconGitBranch, IconTrash, IconWarning } from '@posthog/icons'import {LemonButton,LemonCheckbox,@@ -16,40 +15,31 @@ import {LemonDialog,LemonDropdown,LemonInput,- LemonSegmentedButton,LemonSwitch,Link,Tooltip,} from '@posthog/lemon-ui'import { FEATURE_FLAGS } from 'lib/constants'-import { IconMonitor, SortableDragIcon } from 'lib/lemon-ui/icons'+import { SortableDragIcon } from 'lib/lemon-ui/icons'import { LemonField } from 'lib/lemon-ui/LemonField'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { Customization } from 'scenes/surveys/survey-appearance/SurveyCustomization'import { SurveyTranslations } from 'scenes/surveys/SurveyTranslations'+import { getSurveyWithTranslatedContent } from 'scenes/surveys/surveyTranslationUtils'import { sanitizeSurveyAppearance, validateSurveyAppearance } from 'scenes/surveys/utils'import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'-import {- RatingSurveyQuestion,- Survey,- SurveyQuestion,- SurveyQuestionBranchingType,- SurveyQuestionType,- SurveyType,-} from '~/types'+import { Survey, SurveyQuestion, SurveyQuestionType, SurveyType } from '~/types'import { SurveyBranchingFlowModal } from './branching-flow/SurveyBranchingFlowModal'-import { defaultSurveyAppearance, defaultSurveyFieldValues, NewSurvey, SurveyQuestionLabel } from './constants'+import { defaultSurveyFieldValues, NewSurvey, SurveyQuestionLabel } from './constants'import { CopySurveyLink } from './CopySurveyLink'-import { HTMLEditor } from './SurveyAppearanceUtils'-import { SurveyEditQuestionGroup } from './SurveyEditQuestionRow'+import { HostedSurveyCanvas } from './hosted-canvas/HostedSurveyCanvas'+import { HostedSurveySettingsPanel } from './hosted-canvas/HostedSurveySettingsPanel'import { surveyLogic } from './surveyLogic'import { SurveyResponsesCollection } from './SurveyResponsesCollection'-import { getSurveyWithTranslatedContent } from './surveyTranslationUtils'-import { sanitizeHTML } from './utils'import { AddQuestionButton } from './wizard/AddQuestionButton'function getHostedSurveyUrl(surveyId: string): string {@@ -65,457 +55,6 @@ function moveQuestion(questions: SurveyQuestion[], from: number, to: number): Sureturn nextQuestions.map((q) => ({ ...q }))}-function getHostedPreviewAppearance(survey: Survey | NewSurvey): NonNullable<(Survey | NewSurvey)['appearance']> {- return {- ...defaultSurveyAppearance,- backgroundColor: '#ffffff',- borderColor: 'rgba(17, 17, 17, 0.10)',- borderRadius: '10px',- submitButtonColor: '#111111',- submitButtonTextColor: '#ffffff',- ratingButtonColor: '#ffffff',- ratingButtonActiveColor: '#111111',- inputBackground: '#ffffff',- textSubtleColor: '#6b6b6b',- ...survey.appearance,- hideCancelButton: true,- surveyPopupDelaySeconds: undefined,- }-}--function getPreviewProgressValue(survey: Survey | NewSurvey, previewPageIndex: number): number {- if (previewPageIndex >= survey.questions.length) {- return 100- }-- if (survey.questions.length === 0) {- return 0- }-- return Math.round(((previewPageIndex + 1) / survey.questions.length) * 100)-}--interface HostedPreviewCSSProperties extends CSSProperties {- '--ph-survey-progress-value': string- '--ph-survey-page-background': string- '--ph-survey-page-text': string- '--ph-survey-page-text-subtle': string- '--ph-survey-page-progress-bar': string- '--ph-survey-page-progress-track': string- '--ph-survey-pill-background': string- '--ph-survey-card-shadow': string- '--ph-survey-input-background': string- '--ph-survey-background-color': string- '--ph-survey-border-color': string- '--ph-survey-border-radius': string- '--ph-survey-text-primary-color': string- '--ph-survey-input-text-color': string- '--ph-survey-text-subtle-color': string- '--ph-survey-submit-button-color': string- '--ph-survey-submit-button-text-color': string- '--ph-survey-rating-bg-color': string- '--ph-survey-rating-text-color': string- '--ph-survey-rating-active-bg-color': string- '--ph-survey-rating-active-text-color': string-}--type PreviewResponse = string | string[] | number | null--const RATING_EMOJI_PREVIEW = ['\u{1F621}', '\u{1F641}', '\u{1F610}', '\u{1F642}', '\u{1F60D}']--function getLuminance(color: string | undefined): number | null {- if (!color) {- return null- }-- let hex = color.trim().toLowerCase()- if (hex === 'white') {- hex = '#ffffff'- } else if (hex === 'black') {- hex = '#000000'- }-- if (!hex.startsWith('#')) {- return null- }- if (hex.length === 4) {- hex = `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`- }- if (hex.length !== 7) {- return null- }-- const red = parseInt(hex.slice(1, 3), 16) / 255- const green = parseInt(hex.slice(3, 5), 16) / 255- const blue = parseInt(hex.slice(5, 7), 16) / 255- return 0.2126 * red + 0.7152 * green + 0.0722 * blue-}--function getContrastingTextColor(background: string | undefined): string | null {- const luminance = getLuminance(background)- if (luminance === null) {- return null- }- return luminance > 0.55 ? '#111111' : '#ffffff'-}--function hasPreviewResponse(question: SurveyQuestion, response: PreviewResponse): boolean {- if (question.type === SurveyQuestionType.Link) {- return true- }- if (question.optional) {- return true- }- if (Array.isArray(response)) {- return response.length > 0- }- if (typeof response === 'string') {- return response.trim().length > 0- }- return response !== null-}--function SurveyPreviewDescription({ question }: { question: SurveyQuestion }): JSX.Element | null {- if (!question.description) {- return null- }-- if (question.descriptionContentType === 'html') {- return (- <div- className="survey-question-description"- dangerouslySetInnerHTML={{ __html: sanitizeHTML(question.description) }}- />- )- }-- return <p className="survey-question-description">{question.description}</p>-}--function HostedSurveyQuestionPreview({- question,- response,- onResponseChange,- onSubmit,-}: {- question: SurveyQuestion- response: PreviewResponse- onResponseChange: (response: PreviewResponse) => void- onSubmit: (response: PreviewResponse) => void-}): JSX.Element {- const buttonText = question.buttonText || (question.type === SurveyQuestionType.Link ? 'Continue' : 'Submit')- const canSubmit = hasPreviewResponse(question, response)-- const submitButton = (- <div className="bottom-section">- <button- type="button"- className="form-submit"- disabled={!canSubmit}- onClick={() => {- if (canSubmit) {- onSubmit(response)- }- }}- >- {buttonText}- </button>- <span className="survey-keyhint">- <span className="survey-keyhint-row">- <kbd className="survey-kbd">{'\u21B5'}</kbd>- <span className="survey-keyhint-label">submit</span>- </span>- </span>- </div>- )-- return (- <form className="survey-form" name="surveyForm">- <div className="survey-box" data-question-index="0">- <div className="question-container">- <div>- <h1 className="survey-question">{question.question || 'Untitled question'}</h1>- <SurveyPreviewDescription question={question} />- </div>- {question.type === SurveyQuestionType.Open ? (- <textarea- value={typeof response === 'string' ? response : ''}- placeholder="Start typing..."- onChange={(event) => onResponseChange(event.target.value)}- />- ) : null}- {question.type === SurveyQuestionType.Link ? (- <Link to={question.link ?? '#'} target="_blank">- {question.link || 'https://posthog.com'}- </Link>- ) : null}- {(question.type === SurveyQuestionType.SingleChoice ||- question.type === SurveyQuestionType.MultipleChoice) && (- <fieldset>- <legend className="sr-only">{question.question}</legend>- <div className="multiple-choice-options">- {question.choices.map((choice, choiceIndex) => {- const values = Array.isArray(response) ? response : []- const checked =- question.type === SurveyQuestionType.SingleChoice- ? response === choice- : values.includes(choice)-- return (- <label key={choiceIndex}>- <span className="response-choice">- <input- type={- question.type === SurveyQuestionType.SingleChoice- ? 'radio'- : 'checkbox'- }- checked={checked}- onChange={() => {- if (question.type === SurveyQuestionType.SingleChoice) {- onResponseChange(choice)- if (question.skipSubmitButton) {- onSubmit(choice)- }- return- }-- const nextValues = checked- ? values.filter((value) => value !== choice)- : [...values, choice]- onResponseChange(nextValues)- }}- />- {choice}- </span>- </label>- )- })}- </div>- </fieldset>- )}- {question.type === SurveyQuestionType.Rating ? (- <div className="rating-section">- <div- className={- question.display === 'emoji' ? 'rating-options-emoji' : 'rating-options-number'- }- >- {Array.from(- {- length: question.scale === 10 ? 11 : question.scale,- },- (_, index) => {- const value = question.scale === 10 ? index : index + 1- const isActive = response === value- return (- <button- key={value}- type="button"- className={- question.display === 'emoji'- ? `ratings-emoji ${isActive ? 'rating-active' : ''}`- : `ratings-number ${isActive ? 'rating-active' : ''}`- }- onClick={() => {- onResponseChange(value)- if (question.skipSubmitButton) {- onSubmit(value)- }- }}- >- {question.display === 'emoji'- ? RATING_EMOJI_PREVIEW[index] || RATING_EMOJI_PREVIEW[3]- : value}- </button>- )- }- )}- </div>- <div className="rating-text">- <span>{question.lowerBoundLabel}</span>- <span>{question.upperBoundLabel}</span>- </div>- </div>- ) : null}- {submitButton}- </div>- </div>- </form>- )-}--function HostedSurveyConfirmationPreview({ survey }: { survey: Survey | NewSurvey }): JSX.Element {- const appearance = survey.appearance ?? {}- const closeButtonText = appearance.thankYouMessageCloseButtonText-- return (- <div className="thank-you-message">- <h1 className="thank-you-message-header">{appearance.thankYouMessageHeader || 'Thank you!'}</h1>- {appearance.thankYouMessageDescription ? (- appearance.thankYouMessageDescriptionContentType === 'html' ? (- <div- className="thank-you-message-body"- dangerouslySetInnerHTML={{ __html: sanitizeHTML(appearance.thankYouMessageDescription) }}- />- ) : (- <p className="thank-you-message-body">{appearance.thankYouMessageDescription}</p>- )- ) : null}- {closeButtonText ? (- <div className="bottom-section">- <button type="button" className="form-submit" disabled>- {closeButtonText}- </button>- </div>- ) : null}- </div>- )-}--function HostedSurveyPreview({- survey,- previewPageIndex,- onPreviewPageChange,-}: {- survey: Survey | NewSurvey- previewPageIndex: number- onPreviewPageChange: (pageIndex: number) => void-}): JSX.Element {- const [viewport, setViewport] = useState<'desktop' | 'mobile'>('desktop')- const [previewResponses, setPreviewResponses] = useState<Record<number, PreviewResponse>>({})- const totalPages = survey.questions.length + (survey.appearance?.displayThankYouMessage ? 1 : 0)- const hostedAppearance = getHostedPreviewAppearance(survey)- const previewProgress = getPreviewProgressValue(survey, previewPageIndex)- const cardBg = hostedAppearance.inputBackground || hostedAppearance.backgroundColor || '#ffffff'- const primaryText =- hostedAppearance.textColor || hostedAppearance.inputTextColor || getContrastingTextColor(cardBg) || '#111111'- const submitButtonColor = hostedAppearance.submitButtonColor || '#111111'- const ratingButtonColor = hostedAppearance.ratingButtonColor || cardBg- const ratingActiveColor = hostedAppearance.ratingButtonActiveColor || submitButtonColor- const previewStyles: HostedPreviewCSSProperties = {- '--ph-survey-progress-value': `${previewProgress}%`,- '--ph-survey-page-background': hostedAppearance.backgroundColor || '#ffffff',- '--ph-survey-page-text': primaryText,- '--ph-survey-page-text-subtle': hostedAppearance.textSubtleColor || '#6b6b6b',- '--ph-survey-page-progress-bar': submitButtonColor,- '--ph-survey-page-progress-track': 'rgba(17, 17, 17, 0.08)',- '--ph-survey-pill-background': 'rgba(255, 255, 255, 0.7)',- '--ph-survey-card-shadow': '0 1px 2px rgba(17, 17, 17, 0.04), 0 2px 8px rgba(17, 17, 17, 0.04)',- '--ph-survey-input-background': cardBg,- '--ph-survey-background-color': cardBg,- '--ph-survey-border-color': hostedAppearance.borderColor || 'rgba(17, 17, 17, 0.10)',- '--ph-survey-border-radius': hostedAppearance.borderRadius || '10px',- '--ph-survey-text-primary-color': primaryText,- '--ph-survey-input-text-color': primaryText,- '--ph-survey-text-subtle-color': hostedAppearance.textSubtleColor || '#6b6b6b',- '--ph-survey-submit-button-color': submitButtonColor,- '--ph-survey-submit-button-text-color':- hostedAppearance.submitButtonTextColor || getContrastingTextColor(submitButtonColor) || '#ffffff',- '--ph-survey-rating-bg-color': ratingButtonColor,- '--ph-survey-rating-text-color': getContrastingTextColor(ratingButtonColor) || primaryText,- '--ph-survey-rating-active-bg-color': ratingActiveColor,- '--ph-survey-rating-active-text-color': getContrastingTextColor(ratingActiveColor) || '#ffffff',- }- const previewQuestion = survey.questions[previewPageIndex]- const isConfirmationPreview = previewPageIndex >= survey.questions.length-- const submitPreviewResponse = (response: PreviewResponse): void => {- const nextStep = getNextSurveyStep(survey, previewPageIndex, response)- if (nextStep === SurveyQuestionBranchingType.End && !survey.appearance?.displayThankYouMessage) {- return- }- onPreviewPageChange(nextStep === SurveyQuestionBranchingType.End ? survey.questions.length : nextStep)- }-- return (- <aside className="xl:sticky xl:top-16 flex min-w-0 flex-col gap-3">- <div className="flex flex-wrap items-center justify-between gap-2">- <div>- <h3 className="mb-0 text-sm font-semibold uppercase tracking-wide text-secondary">Preview</h3>- <p className="mb-0 text-xs text-secondary">- {totalPages > 0 ? `Step ${Math.min(previewPageIndex + 1, totalPages)} of ${totalPages}` : null}- </p>- </div>- <LemonSegmentedButton- size="small"- value={viewport}- onChange={setViewport}- options={[- { label: <IconMonitor />, value: 'desktop', tooltip: 'Desktop preview' },- { label: <IconPhone />, value: 'mobile', tooltip: 'Mobile preview' },- ]}- />- </div>- <div className="HostedSurveyPublicPreview rounded border bg-surface-primary p-3 shadow-sm">- <div- className={- viewport === 'mobile'- ? 'PostHogHostedSurvey HostedSurveyPreviewFrame HostedSurveyPreviewFrame--mobile'- : 'PostHogHostedSurvey HostedSurveyPreviewFrame'- }- style={previewStyles}- >- <div className="survey-progress-wrap">- <div- className="survey-progress-track"- role="progressbar"- aria-label="Survey progress"- aria-valuemin={0}- aria-valuemax={100}- aria-valuenow={previewProgress}- >- <span className="survey-progress-bar" />- </div>- </div>- <div className="survey-stage">- <div className="posthog-survey-container">- {isConfirmationPreview || !previewQuestion ? (- <HostedSurveyConfirmationPreview survey={survey} />- ) : (- <HostedSurveyQuestionPreview- question={previewQuestion}- response={previewResponses[previewPageIndex] ?? null}- onResponseChange={(response) =>- setPreviewResponses((responses) => ({- ...responses,- [previewPageIndex]: response,- }))- }- onSubmit={submitPreviewResponse}- />- )}- </div>- </div>- {!hostedAppearance.whiteLabel ? <div className="footer-branding">Survey by PostHog</div> : null}- </div>- </div>- <div className="flex items-center justify-between gap-2">- <LemonButton- type="secondary"- size="small"- icon={<IconChevronDown className="rotate-90" />}- disabledReason={previewPageIndex <= 0 ? 'Already at the first step' : undefined}- onClick={() => onPreviewPageChange(Math.max(previewPageIndex - 1, 0))}- >- Previous- </LemonButton>- <LemonButton- type="secondary"- size="small"- sideIcon={<IconChevronDown className="-rotate-90" />}- disabledReason={- previewPageIndex >= totalPages - 1 || totalPages === 0 ? 'Already at the last step' : undefined- }- onClick={() => onPreviewPageChange(Math.min(previewPageIndex + 1, totalPages - 1))}- >- Next- </LemonButton>- </div>- </aside>- )-}-function HostedSurveyQuestionRail({id,survey,@@ -782,59 +321,6 @@ function HostedSurveyUrlParamsDropdown(): JSX.Element {)}-function HostedSurveyConfirmationEditor(): JSX.Element {- const { survey } = useValues(surveyLogic)- const { setSurveyValue } = useActions(surveyLogic)-- return (- <div className="flex flex-col gap-3">- <LemonField.Pure label="Thank you header">- <LemonInput- value={survey.appearance?.thankYouMessageHeader ?? ''}- onChange={(thankYouMessageHeader) =>- setSurveyValue('appearance', {- ...survey.appearance,- thankYouMessageHeader,- })- }- placeholder="Thank you for your feedback!"- />- </LemonField.Pure>- <LemonField.Pure label="Thank you description">- <HTMLEditor- value={survey.appearance?.thankYouMessageDescription ?? ''}- onChange={(thankYouMessageDescription) =>- setSurveyValue('appearance', {- ...survey.appearance,- thankYouMessageDescription,- })- }- activeTab={survey.appearance?.thankYouMessageDescriptionContentType ?? 'text'}- onTabChange={(key) =>- setSurveyValue('appearance', {- ...survey.appearance,- thankYouMessageDescriptionContentType: key === 'html' ? 'html' : 'text',- })- }- textPlaceholder="We really appreciate it."- />- </LemonField.Pure>- <LemonField.Pure label="Button text">- <LemonInput- value={survey.appearance?.thankYouMessageCloseButtonText ?? ''}- onChange={(thankYouMessageCloseButtonText) =>- setSurveyValue('appearance', {- ...survey.appearance,- thankYouMessageCloseButtonText,- })- }- placeholder="Close"- />- </LemonField.Pure>- </div>- )-}-function HostedSurveyEditorHeader({id,survey,@@ -855,64 +341,58 @@ function HostedSurveyEditorHeader({onConvertToInApp: () => void}): JSX.Element {return (- <header className="rounded border bg-surface-primary p-3">- <div className="flex flex-col gap-3 xl:flex-row xl:items-start xl:justify-between">- <div className="flex min-w-0 flex-1 flex-col gap-2">- <div className="flex items-center gap-2">- <span className="rounded bg-accent-highlight px-2 py-0.5 text-xs font-semibold text-accent">- Hosted survey- </span>- <span className="text-xs text-secondary">One question at a time</span>- </div>- <div className="grid min-w-0 gap-2 lg:grid-cols-[minmax(260px,0.55fr)_minmax(220px,0.45fr)]">- <LemonInput- value={survey.name}- onChange={onNameChange}- placeholder="Untitled hosted survey"- className="font-semibold"- />- <LemonInput- value={survey.description ?? ''}- onChange={onDescriptionChange}- placeholder="Internal description"- />- </div>- </div>- <div className="flex shrink-0 flex-wrap items-center gap-2">- <LemonButton type="secondary" size="small" onClick={onConvertToInApp}>- Convert to in-app- </LemonButton>- {hostedSurveyUrl ? (- <LemonButton- type="secondary"- size="small"- icon={<IconExternal />}- to={hostedSurveyUrl}- targetBlank- >- Open- </LemonButton>- ) : null}- <LemonButton- data-attr="cancel-survey"- type="secondary"- loading={surveyLoading}- onClick={onCancel}- size="small"- >- Cancel- </LemonButton>- <LemonButton- type="primary"- data-attr="save-survey"- htmlType="submit"- loading={surveyLoading}- form="survey"- size="small"- >- {id === 'new' ? 'Save as draft' : 'Save'}+ <header className="flex flex-col gap-3 xl:flex-row xl:items-end xl:justify-between">+ <div className="grid min-w-0 flex-1 gap-3 lg:grid-cols-[minmax(260px,0.55fr)_minmax(220px,0.45fr)]">+ <LemonField.Pure label="Survey name" htmlFor="hosted-survey-name">+ <LemonInput+ id="hosted-survey-name"+ value={survey.name}+ onChange={onNameChange}+ placeholder="Untitled hosted survey"+ className="font-semibold"+ />+ </LemonField.Pure>+ <LemonField.Pure+ label="Internal description"+ info="Not shown to respondents. Helps your team find this survey later."+ htmlFor="hosted-survey-description"+ >+ <LemonInput+ id="hosted-survey-description"+ value={survey.description ?? ''}+ onChange={onDescriptionChange}+ placeholder="What this survey is for"+ />+ </LemonField.Pure>+ </div>+ <div className="flex shrink-0 flex-wrap items-center gap-2">+ <LemonButton type="secondary" size="small" onClick={onConvertToInApp}>+ Convert to in-app+ </LemonButton>+ {hostedSurveyUrl ? (+ <LemonButton type="secondary" size="small" icon={<IconExternal />} to={hostedSurveyUrl} targetBlank>+ Open</LemonButton>- </div>+ ) : null}+ <LemonButton+ data-attr="cancel-survey"+ type="secondary"+ loading={surveyLoading}+ onClick={onCancel}+ size="small"+ >+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ data-attr="save-survey"+ htmlType="submit"+ loading={surveyLoading}+ form="survey"+ size="small"+ >+ {id === 'new' ? 'Save as draft' : 'Save'}+ </LemonButton></div></header>)@@ -932,19 +412,33 @@ export function HostedSurveyEdit({ id }: { id: string }): JSX.Element {} = useActions(surveyLogic)const { featureFlags } = useValues(featureFlagLogic)const [showFlowModal, setShowFlowModal] = useState(false)+ const [viewport, setViewport] = useState<'desktop' | 'mobile'>('desktop')const surveyTranslationsEnabled = !!featureFlags[FEATURE_FLAGS.SURVEYS_TRANSLATIONS]+ const activeLanguage = surveyTranslationsEnabled ? editingLanguage : null+ // Translation-aware view of the survey for the canvas to render. Edits made+ // on the canvas still flow through surveyLogic against the raw survey, so+ // text edits while a non-default language is active won't write to the+ // wrong field — but they also won't update translations. Use the+ // Translations section below the canvas for that.+ const previewSurvey = useMemo(+ () => getSurveyWithTranslatedContent(survey, activeLanguage),+ [survey, activeLanguage]+ )const maxPageIndex = Math.max(survey.questions.length + (survey.appearance?.displayThankYouMessage ? 1 : 0) - 1, 0)const activePageIndex = Math.min(selectedPageIndex ?? 0, maxPageIndex)- const activeQuestion = survey.questions[activePageIndex]const isConfirmationSelected =!!survey.appearance?.displayThankYouMessage && activePageIndex === survey.questions.length- const previewSurvey = useMemo(- () => getSurveyWithTranslatedContent(survey, surveyTranslationsEnabled ? editingLanguage : null),- [editingLanguage, survey, surveyTranslationsEnabled]- )const hostedSurveyUrl = id === 'new' ? null : getHostedSurveyUrl(id)+ const removeConfirmationScreen = (): void => {+ setSurveyValue('appearance', {+ ...survey.appearance,+ displayThankYouMessage: false,+ })+ setSelectedPageIndex(Math.max(survey.questions.length - 1, 0))+ }+const runAfterBranchingConfirmation = (action: () => void, description: JSX.Element): void => {if (!hasBranchingLogic) {action()@@ -1058,7 +552,7 @@ export function HostedSurveyEdit({ id }: { id: string }): JSX.Element {onCancel={handleCancelClick}onConvertToInApp={convertToInAppSurvey}/>- <div className="grid min-h-[640px] grid-cols-1 gap-4 xl:grid-cols-[300px_minmax(420px,0.9fr)_minmax(520px,1.1fr)]">+ <div className="grid min-h-[640px] grid-cols-1 gap-4 xl:grid-cols-[300px_minmax(0,1fr)]"><HostedSurveyQuestionRailid={id}survey={survey}@@ -1077,182 +571,143 @@ export function HostedSurveyEdit({ id }: { id: string }): JSX.Element {onDeleteQuestion={deleteSurveyQuestion}onIframeEmbeddingChange={(checked) => setSurveyValue('enable_iframe_embedding', checked)}/>- <main className="flex min-w-0 flex-col gap-4">- <section className="rounded border bg-surface-primary p-5">- <div className="mb-5 flex flex-wrap items-start justify-between gap-2 border-b pb-4">- <div>- <p className="mb-1 text-xs font-semibold uppercase tracking-wide text-secondary">- {isConfirmationSelected ? 'End screen' : `Step ${activePageIndex + 1}`}- </p>- <h2 className="mb-0 text-base font-semibold">- {isConfirmationSelected- ? 'Confirmation message'- : activeQuestion?.question || 'Untitled question'}- </h2>- <p className="mb-0 text-xs text-secondary">- {isConfirmationSelected- ? 'Shown after the final answer.'- : activeQuestion- ? SurveyQuestionLabel[activeQuestion.type]- : 'Question'}- </p>- </div>- {isConfirmationSelected ? (- <LemonButton- type="secondary"- status="danger"- size="small"- icon={<IconTrash />}- onClick={() => {- setSurveyValue('appearance', {- ...survey.appearance,- displayThankYouMessage: false,- })- setSelectedPageIndex(Math.max(survey.questions.length - 1, 0))- }}- >- Remove- </LemonButton>- ) : null}- </div>- {isConfirmationSelected ? (- <HostedSurveyConfirmationEditor />- ) : (- <SurveyEditQuestionGroup- index={activePageIndex}- question={- survey.questions[activePageIndex] as SurveyQuestion | RatingSurveyQuestion- }- />- )}- </section>- {surveyTranslationsEnabled ? (- <section className="rounded border bg-surface-primary p-5">- <div className="mb-4 border-b pb-3">- <p className="mb-1 text-xs font-semibold uppercase tracking-wide text-secondary">- Languages- </p>- <h2 className="mb-0 text-base font-semibold">Translations</h2>- <p className="mb-0 text-xs text-secondary">- Localize the hosted survey without changing the default flow.- </p>- </div>- <div className="flex flex-col gap-3">- {editingLanguage ? (- <div className="rounded border border-warning bg-warning-highlight p-3 text-sm">- Editing translated survey content. Question order and settings stay in the- default language.- </div>- ) : null}- <SurveyTranslations />- {editingLanguage ? (- <LemonButton- type="secondary"- size="small"- onClick={() => setEditingLanguage(null)}- className="w-max"- >- Edit default language- </LemonButton>- ) : null}+ <div className="HostedSurveyCanvasLayout">+ <HostedSurveyCanvas+ survey={previewSurvey}+ activePageIndex={activePageIndex}+ isConfirmation={isConfirmationSelected}+ viewport={viewport}+ />+ <HostedSurveySettingsPanel+ activePageIndex={activePageIndex}+ isConfirmation={isConfirmationSelected}+ viewport={viewport}+ onViewportChange={setViewport}+ onRemoveConfirmation={removeConfirmationScreen}+ />+ </div>+ </div>++ {surveyTranslationsEnabled ? (+ <section className="rounded border bg-surface-primary p-5">+ <div className="mb-4 border-b pb-3">+ <p className="mb-1 text-xs font-semibold uppercase tracking-wide text-secondary">+ Languages+ </p>+ <h2 className="mb-0 text-base font-semibold">Translations</h2>+ <p className="mb-0 text-xs text-secondary">+ Localize the hosted survey without changing the default flow.+ </p>+ </div>+ <div className="flex flex-col gap-3">+ {editingLanguage ? (+ <div className="rounded border border-warning bg-warning-highlight p-3 text-sm">+ Editing translated survey content. Question order and settings stay in the default+ language.</div>- </section>- ) : null}- <LemonCollapse- className="bg-surface-primary rounded border"- panels={[- {- key: 'appearance',- header: 'Style',- content: (- <LemonField name="appearance" label="">- {({ onChange }) => (- <Customization- survey={survey}- hasBranchingLogic={hasBranchingLogic}- deleteBranchingLogic={deleteBranchingLogic}- hasRatingButtons={survey.questions.some(- (question) => question.type === SurveyQuestionType.Rating- )}- hasPlaceholderText={survey.questions.some(- (question) => question.type === SurveyQuestionType.Open- )}- onAppearanceChange={(appearance) => {- const newAppearance = sanitizeSurveyAppearance({- ...survey.appearance,- ...appearance,- })- onChange(newAppearance)- if (newAppearance) {- setSurveyManualErrors(- validateSurveyAppearance(- newAppearance,- true,- SurveyType.ExternalSurvey- )- )- }- }}- validationErrors={surveyErrors?.appearance}- />+ ) : null}+ <SurveyTranslations />+ {editingLanguage ? (+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => setEditingLanguage(null)}+ className="w-max"+ >+ Edit default language+ </LemonButton>+ ) : null}+ </div>+ </section>+ ) : null}++ <LemonCollapse+ className="bg-surface-primary rounded border"+ panels={[+ {+ key: 'appearance',+ header: 'Style',+ content: (+ <LemonField name="appearance" label="">+ {({ onChange }) => (+ <Customization+ survey={survey}+ hasBranchingLogic={hasBranchingLogic}+ deleteBranchingLogic={deleteBranchingLogic}+ hasRatingButtons={survey.questions.some(+ (question) => question.type === SurveyQuestionType.Rating+ )}+ hasPlaceholderText={survey.questions.some(+ (question) => question.type === SurveyQuestionType.Open)}- </LemonField>- ),- },- {- key: 'collection',- header: 'Collection',- content: (- <div className="flex flex-col gap-4">- <LemonField.Pure label={<h3 className="mb-0">Completion limit</h3>}>- <div className="flex flex-wrap items-center gap-2">- <LemonCheckbox- checked={!!survey.responses_limit}- onChange={(checked) =>- setSurveyValue('responses_limit', checked ? 100 : null)- }- label="Stop collecting after"- />- <LemonInput- type="number"- min={1}- size="small"- value={survey.responses_limit || NaN}- onChange={(value) => {- setSurveyValue(- 'responses_limit',- value && value > 0 ? value : null- )- }}- className="w-20"- />- responses- </div>- </LemonField.Pure>- <SurveyResponsesCollection />+ onAppearanceChange={(appearance) => {+ const newAppearance = sanitizeSurveyAppearance({+ ...survey.appearance,+ ...appearance,+ })+ onChange(newAppearance)+ if (newAppearance) {+ setSurveyManualErrors(+ validateSurveyAppearance(+ newAppearance,+ true,+ SurveyType.ExternalSurvey+ )+ )+ }+ }}+ validationErrors={surveyErrors?.appearance}+ />+ )}+ </LemonField>+ ),+ },+ {+ key: 'collection',+ header: 'Collection',+ content: (+ <div className="flex flex-col gap-4">+ <LemonField.Pure label={<h3 className="mb-0">Completion limit</h3>}>+ <div className="flex flex-wrap items-center gap-2">+ <LemonCheckbox+ checked={!!survey.responses_limit}+ onChange={(checked) =>+ setSurveyValue('responses_limit', checked ? 100 : null)+ }+ label="Stop collecting after"+ />+ <LemonInput+ type="number"+ min={1}+ size="small"+ value={survey.responses_limit || NaN}+ onChange={(value) => {+ setSurveyValue('responses_limit', value && value > 0 ? value : null)+ }}+ className="w-20"+ />+ responses</div>- ),- },- ]}- />- {hasBranchingLogic ? (- <LemonButton- data-attr="preview-survey-branching"- type="secondary"- className="w-max"- icon={<IconGitBranch />}- onClick={() => setShowFlowModal(true)}- >- Preview branching flow- </LemonButton>- ) : null}- </main>- <HostedSurveyPreview- survey={previewSurvey}- previewPageIndex={activePageIndex}- onPreviewPageChange={setSelectedPageIndex}- />- </div>+ </LemonField.Pure>+ <SurveyResponsesCollection />+ </div>+ ),+ },+ ]}+ />++ {hasBranchingLogic ? (+ <LemonButton+ data-attr="preview-survey-branching"+ type="secondary"+ className="w-max"+ icon={<IconGitBranch />}+ onClick={() => setShowFlowModal(true)}+ >+ Preview branching flow+ </LemonButton>+ ) : null}+{id === 'new' ? (<div className="flex items-center gap-2 rounded border bg-accent-highlight p-3 text-sm"><IconWarning className="text-warning" />diff --git a/frontend/src/scenes/surveys/hosted-canvas/HostedSurveyCanvas.scss b/frontend/src/scenes/surveys/hosted-canvas/HostedSurveyCanvas.scssnew file mode 100644index 000000000000..50fe2cecd9bd--- /dev/null+++ b/frontend/src/scenes/surveys/hosted-canvas/HostedSurveyCanvas.scss@@ -0,0 +1,293 @@+// Inline-editable affordances on the hosted survey canvas. The canvas should+// feel like editing text in place — no input chrome, just the rendered text+// with a cursor when active.+.HostedSurveyCanvasStage {+ display: flex;+ flex-direction: column;+ align-items: stretch;+ min-height: min(85dvh, 900px);+ overflow: hidden;+ background: var(--bg-light);+ border: 1px solid var(--border);+ border-radius: var(--radius);++ // Desktop preview frame fills the stage so the question content can+ // breathe inside a real viewport, not a tight 520px card.+ .PostHogHostedSurvey.HostedSurveyPreviewFrame {+ border: none;+ border-radius: 0;+ }++ .PostHogHostedSurvey.HostedSurveyPreviewFrame:not(.HostedSurveyPreviewFrame--mobile) {+ flex: 1;+ min-height: 0;+ padding: clamp(2rem, 5dvh, 4rem) clamp(1.5rem, 4vw, 2.5rem);+ }++ // Mobile preview replicates the real `@media (max-width: 640px)` rules+ // from hosted-survey.css. Because the canvas runs in a desktop browser,+ // those media-query rules never fire on their own — we have to mimic them+ // here so the mobile preview accurately reflects what respondents see on+ // a phone.+ .HostedSurveyPreviewFrame--mobile {+ // 1. Submit button stretches to full width on phone-sized screens.+ .form-submit {+ width: 100%;+ min-width: 0;+ }++ // 2. Keyboard hints are hidden on touch devices (the base CSS only+ // reveals them under `hover: hover` + `pointer: fine`).+ .survey-keyhint {+ display: none;+ }++ // 3. Titles compress slightly on phones.+ .survey-question,+ .thank-you-message-header {+ font-size: 1.5rem;+ }+ }++ // Display elements (h1.survey-question, p.survey-question-description,+ // span.form-submit, etc.) keep their natural styling — we ONLY add an edit+ // affordance. No font/padding/background/border-radius reset on these so+ // the rendered look (e.g. .form-submit's rounded pill) stays intact.+ .inline-editable {+ cursor: text;+ transition:+ background-color 120ms ease,+ box-shadow 120ms ease;+ }++ // Placeholder style helps distinguish "no content yet" from a real value+ // for prose-like elements (title, description). Excluded on .form-submit+ // so the empty submit button doesn't fade or italicize.+ .inline-editable--placeholder:not(.form-submit) {+ font-style: italic;+ opacity: 0.55;+ }++ .inline-editable--invalid {+ text-decoration: underline wavy var(--danger);+ text-underline-offset: 4px;+ }++ // Focus indicator — outline ring sits 2px outside the rendered shape so+ // it never masks the element's own background (e.g. submit button pill).+ .inline-editable:focus,+ .inline-editable:focus-visible {+ outline: 2px solid var(--accent, rgb(17 17 17 / 28%));+ outline-offset: 2px;+ }++ // Inline display contexts (choice text + ":" suffix, submit button) need+ // width: auto. Block contexts (title, description) want width: 100%.+ span.inline-editable {+ display: inline-block;+ }++ .response-choice .inline-editable {+ width: auto;+ }++ // The submit button uses a <span class="form-submit inline-editable"> in+ // display mode. Make it center its text the way <button> does so the pill+ // looks like a real button and not a left-aligned padded label.+ span.form-submit.inline-editable {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ text-align: center;+ }++ // Hover affordance for prose elements only — never alter the rendered+ // background of pill-styled elements.+ @media (hover: hover) {+ .inline-editable:not(.form-submit):hover:not(:focus) {+ background-color: rgb(17 17 17 / 4%);+ border-radius: 3px;+ box-shadow: 0 0 0 2px rgb(17 17 17 / 4%);+ }+ }+}++// Editing-mode chrome reset for inputs/textareas. Deliberately lives OUTSIDE+// the .HostedSurveyCanvasStage block so it has class-only specificity (0,1,1).+// Any `.PostHogHostedSurvey .form-submit` / `.PostHogHostedSurvey .survey-+// question` rule at (0,2,0) then wins for font-size, font-weight, color, etc.+// Result: clicking in swaps the rendered element for an input that visually+// matches it — same font size, weight, color, and padding context.+input.inline-editable,+textarea.inline-editable {+ width: 100%;+ min-width: 0;+ max-width: 100%;++ // The base .PostHogHostedSurvey textarea forces min-height: 8rem for the+ // respondent open-text input — undo here or every click on the title+ // blows up into a giant box.+ min-height: 0;+ padding: 0;+ margin: 0;++ // Font properties inherit from the rendered class. .survey-question /+ // .form-submit etc. provide explicit values at higher specificity that+ // win over these — so the input matches its display element's font.+ font-family: inherit;+ font-size: inherit;+ font-weight: inherit;+ line-height: inherit;+ color: inherit;+ letter-spacing: inherit;+ appearance: none;+ cursor: text;+ resize: none;+ background: transparent;+ border: none;+ border-radius: 0;+ outline: none;+ box-shadow: none;++ /* stylelint-disable-next-line property-no-unknown */+ field-sizing: content;+}++textarea.inline-editable {+ height: auto;+ overflow: hidden;+}++// Wrapper that anchors the canvas + settings layout. Stretches both children+// to the same row height so canvas, settings panel, and flow rail share an+// aligned baseline at the top and bottom.+.HostedSurveyCanvasLayout {+ display: grid;+ grid-template-columns: minmax(0, 1fr);+ gap: 1rem;+ align-items: stretch;++ @media (min-width: 1024px) {+ grid-template-columns: minmax(0, 1fr) 320px;+ }++ @media (min-width: 1440px) {+ grid-template-columns: minmax(0, 1fr) 360px;+ }+}++// Choice rows on the canvas — always-visible delete + drag handle so the+// affordances are discoverable without hover hunting.+.HostedSurveyCanvasChoice {+ position: relative;+ display: flex;+ gap: 0.5rem;+ align-items: stretch;+ width: 100%;++ &--dragging {+ opacity: 0.5;+ }++ // The label is the survey-styled pill — flex-fill the row while keeping+ // grip and delete buttons at fixed widths beside it.+ & > label {+ flex: 1;+ min-width: 0;+ }++ // Wrap the editable choice text + the optional ":" suffix so the colon+ // sits flush against the text, not separated by the .response-choice+ // flex gap.+ &__label {+ display: inline-flex;+ gap: 0;+ align-items: baseline;+ min-width: 0;+ }++ &__grip {+ display: inline-flex;+ flex-shrink: 0;+ align-items: center;+ align-self: center;+ justify-content: center;+ width: 1.5rem;+ color: var(--text-secondary);+ cursor: grab;+ opacity: 0.85;+ transition:+ opacity 120ms ease,+ color 120ms ease;++ &:hover,+ &:focus-visible {+ opacity: 1;+ }++ &:active {+ cursor: grabbing;+ }++ &--locked {+ cursor: not-allowed;+ opacity: 0.3;+ }+ }++ // Plain-button trash so we don't fight LemonButton's internal cascade —+ // 32x32 outlined square with a clear red hover state.+ &__delete {+ display: inline-flex;+ flex-shrink: 0;+ align-items: center;+ align-self: center;+ justify-content: center;+ width: 2rem;+ height: 2rem;+ padding: 0;+ font-size: 1rem;+ color: var(--text-secondary, #6b6b6b);+ cursor: pointer;+ background: transparent;+ border: 1px solid var(--border-bold, rgb(17 17 17 / 18%));+ border-radius: 6px;+ transition:+ background-color 120ms ease,+ border-color 120ms ease,+ color 120ms ease;++ &:hover:not(:disabled) {+ color: #b62a1d;+ background: rgb(192 57 43 / 10%);+ border-color: rgb(192 57 43 / 60%);+ }++ &:disabled {+ cursor: not-allowed;+ opacity: 0.4;+ }+ }+}++.HostedSurveyCanvasAddChoice {+ display: inline-flex;+ gap: 0.25rem;+ align-items: center;+ padding: 0.25rem 0.5rem;+ font-size: 0.875rem;+ color: var(--text-secondary);+ cursor: pointer;+ background: transparent;+ border: 1px dashed var(--border-bold, rgb(17 17 17 / 18%));+ border-radius: 6px;+ transition:+ background-color 120ms ease,+ border-color 120ms ease;++ &:hover {+ color: var(--text-primary);+ background: var(--surface-tertiary);+ border-color: var(--accent);+ }+}diff --git a/frontend/src/scenes/surveys/hosted-canvas/HostedSurveyCanvas.tsx b/frontend/src/scenes/surveys/hosted-canvas/HostedSurveyCanvas.tsxnew file mode 100644index 000000000000..e2389755beb6--- /dev/null+++ b/frontend/src/scenes/surveys/hosted-canvas/HostedSurveyCanvas.tsx@@ -0,0 +1,666 @@+import './HostedSurveyCanvas.scss'++import { DndContext, DragEndEvent } from '@dnd-kit/core'+import { SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable'+import { CSS } from '@dnd-kit/utilities'+import { useActions, useValues } from 'kea'+import { type CSSProperties } from 'react'++import { IconPlus, IconTrash } from '@posthog/icons'++import { SortableDragIcon } from 'lib/lemon-ui/icons'+import { defaultSurveyAppearance } from 'scenes/surveys/constants'+import { surveyLogic } from 'scenes/surveys/surveyLogic'+import { sanitizeHTML } from 'scenes/surveys/utils'++import {+ type MultipleSurveyQuestion,+ type RatingSurveyQuestion,+ type Survey,+ type SurveyAppearance,+ type SurveyQuestion,+ SurveyQuestionType,+} from '~/types'++import { type NewSurvey } from '../constants'+import { InlineEditable } from './InlineEditable'++const RATING_EMOJI_PREVIEW = ['\u{1F621}', '\u{1F641}', '\u{1F610}', '\u{1F642}', '\u{1F60D}']++function getLuminance(color: string | undefined): number | null {+ if (!color) {+ return null+ }++ let hex = color.trim().toLowerCase()+ if (hex === 'white') {+ hex = '#ffffff'+ } else if (hex === 'black') {+ hex = '#000000'+ }++ if (!hex.startsWith('#')) {+ return null+ }+ if (hex.length === 4) {+ hex = `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`+ }+ if (hex.length !== 7) {+ return null+ }++ const red = parseInt(hex.slice(1, 3), 16) / 255+ const green = parseInt(hex.slice(3, 5), 16) / 255+ const blue = parseInt(hex.slice(5, 7), 16) / 255+ return 0.2126 * red + 0.7152 * green + 0.0722 * blue+}++function getContrastingTextColor(background: string | undefined): string | null {+ const luminance = getLuminance(background)+ if (luminance === null) {+ return null+ }+ return luminance > 0.55 ? '#111111' : '#ffffff'+}++function buildCanvasAppearance(survey: Survey | NewSurvey): SurveyAppearance {+ return {+ ...defaultSurveyAppearance,+ backgroundColor: '#ffffff',+ borderColor: 'rgba(17, 17, 17, 0.10)',+ borderRadius: '10px',+ submitButtonColor: '#111111',+ submitButtonTextColor: '#ffffff',+ ratingButtonColor: '#ffffff',+ ratingButtonActiveColor: '#111111',+ inputBackground: '#ffffff',+ textSubtleColor: '#6b6b6b',+ ...survey.appearance,+ hideCancelButton: true,+ surveyPopupDelaySeconds: undefined,+ }+}++interface CanvasCSSProperties extends CSSProperties {+ '--ph-survey-progress-value': string+ '--ph-survey-page-background': string+ '--ph-survey-page-text': string+ '--ph-survey-page-text-subtle': string+ '--ph-survey-page-progress-bar': string+ '--ph-survey-page-progress-track': string+ '--ph-survey-pill-background': string+ '--ph-survey-card-shadow': string+ '--ph-survey-input-background': string+ '--ph-survey-background-color': string+ '--ph-survey-border-color': string+ '--ph-survey-border-radius': string+ '--ph-survey-text-primary-color': string+ '--ph-survey-input-text-color': string+ '--ph-survey-text-subtle-color': string+ '--ph-survey-submit-button-color': string+ '--ph-survey-submit-button-text-color': string+ '--ph-survey-rating-bg-color': string+ '--ph-survey-rating-text-color': string+ '--ph-survey-rating-active-bg-color': string+ '--ph-survey-rating-active-text-color': string+}++function buildCanvasStyles(appearance: SurveyAppearance, progress: number): CanvasCSSProperties {+ const cardBg = appearance.inputBackground || appearance.backgroundColor || '#ffffff'+ const primaryText =+ appearance.textColor || appearance.inputTextColor || getContrastingTextColor(cardBg) || '#111111'+ const submitButtonColor = appearance.submitButtonColor || '#111111'+ const ratingButtonColor = appearance.ratingButtonColor || cardBg+ const ratingActiveColor = appearance.ratingButtonActiveColor || submitButtonColor+ return {+ '--ph-survey-progress-value': `${progress}%`,+ '--ph-survey-page-background': appearance.backgroundColor || '#ffffff',+ '--ph-survey-page-text': primaryText,+ '--ph-survey-page-text-subtle': appearance.textSubtleColor || '#6b6b6b',+ '--ph-survey-page-progress-bar': submitButtonColor,+ '--ph-survey-page-progress-track': 'rgba(17, 17, 17, 0.08)',+ // hosted-survey.css uses this for the footer-branding pill background;+ // without it the pill renders transparent against the survey card.+ '--ph-survey-pill-background': 'rgba(255, 255, 255, 0.7)',+ '--ph-survey-card-shadow': '0 1px 2px rgba(17, 17, 17, 0.04), 0 2px 8px rgba(17, 17, 17, 0.04)',+ '--ph-survey-input-background': cardBg,+ '--ph-survey-background-color': cardBg,+ '--ph-survey-border-color': appearance.borderColor || 'rgba(17, 17, 17, 0.10)',+ '--ph-survey-border-radius': appearance.borderRadius || '10px',+ '--ph-survey-text-primary-color': primaryText,+ '--ph-survey-input-text-color': primaryText,+ '--ph-survey-text-subtle-color': appearance.textSubtleColor || '#6b6b6b',+ '--ph-survey-submit-button-color': submitButtonColor,+ '--ph-survey-submit-button-text-color':+ appearance.submitButtonTextColor || getContrastingTextColor(submitButtonColor) || '#ffffff',+ '--ph-survey-rating-bg-color': ratingButtonColor,+ '--ph-survey-rating-text-color': getContrastingTextColor(ratingButtonColor) || primaryText,+ '--ph-survey-rating-active-bg-color': ratingActiveColor,+ '--ph-survey-rating-active-text-color': getContrastingTextColor(ratingActiveColor) || '#ffffff',+ }+}++function getProgress(survey: Survey | NewSurvey, pageIndex: number): number {+ if (pageIndex >= survey.questions.length) {+ return 100+ }+ if (survey.questions.length === 0) {+ return 0+ }+ return Math.round(((pageIndex + 1) / survey.questions.length) * 100)+}++interface HostedSurveyCanvasProps {+ survey: Survey | NewSurvey+ activePageIndex: number+ /** True when active page is the confirmation/thank-you screen. */+ isConfirmation: boolean+ /** Mobile vs desktop frame for visual context. */+ viewport: 'desktop' | 'mobile'+}++export function HostedSurveyCanvas({+ survey,+ activePageIndex,+ isConfirmation,+ viewport,+}: HostedSurveyCanvasProps): JSX.Element {+ const appearance = buildCanvasAppearance(survey)+ const progress = getProgress(survey, activePageIndex)+ const styles = buildCanvasStyles(appearance, progress)+ const activeQuestion = survey.questions[activePageIndex] as SurveyQuestion | undefined+ const frameClassName =+ viewport === 'mobile'+ ? 'PostHogHostedSurvey HostedSurveyPreviewFrame HostedSurveyPreviewFrame--mobile'+ : 'PostHogHostedSurvey HostedSurveyPreviewFrame'++ return (+ <div className="HostedSurveyCanvasStage">+ {/* eslint-disable-next-line react/forbid-dom-props */}+ <div className={frameClassName} style={styles}>+ <div className="survey-progress-wrap">+ <div+ className="survey-progress-track"+ role="progressbar"+ aria-label="Survey progress"+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={progress}+ >+ <span className="survey-progress-bar" />+ </div>+ </div>+ <div className="survey-stage">+ <div className="posthog-survey-container">+ {isConfirmation ? (+ <ConfirmationCanvas survey={survey} />+ ) : activeQuestion ? (+ <QuestionCanvas question={activeQuestion} index={activePageIndex} />+ ) : null}+ </div>+ </div>+ {!appearance.whiteLabel ? <div className="footer-branding">Survey by PostHog</div> : null}+ </div>+ </div>+ )+}++function QuestionCanvas({ question, index }: { question: SurveyQuestion; index: number }): JSX.Element {+ const { survey } = useValues(surveyLogic)+ const { setSurveyValue } = useActions(surveyLogic)++ // Surveys union typing makes a strict per-key updater painful — accept arbitrary+ // values here. Each caller already constrains the value to the matching question+ // type, and the survey form schema validates downstream.+ const updateField = (key: string, value: unknown): void => {+ const next = survey.questions.map((q, idx) => (idx === index ? { ...q, [key]: value } : q))+ setSurveyValue('questions', next)+ }++ const isChoiceQuestion =+ question.type === SurveyQuestionType.SingleChoice || question.type === SurveyQuestionType.MultipleChoice+ const choiceQuestion = isChoiceQuestion ? (question as MultipleSurveyQuestion) : null++ const commitChoices = (choices: string[]): void => {+ if (!choiceQuestion) {+ return+ }+ updateField('choices', choices)+ }++ const updateChoice = (choiceIndex: number, value: string): void => {+ if (!choiceQuestion) {+ return+ }+ const choices = [...(choiceQuestion.choices || [])]+ choices[choiceIndex] = value+ commitChoices(choices)+ }++ const deleteChoice = (choiceIndex: number): void => {+ if (!choiceQuestion) {+ return+ }+ const choices = choiceQuestion.choices || []+ const isDeletingOpen = !!choiceQuestion.hasOpenChoice && choiceIndex === choices.length - 1+ const remaining = choices.filter((_, i) => i !== choiceIndex)+ if (isDeletingOpen) {+ // Deleting the open-ended option also unsets the flag so the bookkeeping stays consistent.+ const next = survey.questions.map((q, idx) =>+ idx === index ? { ...q, choices: remaining, hasOpenChoice: false } : q+ )+ setSurveyValue('questions', next)+ return+ }+ commitChoices(remaining)+ }++ const addChoice = (): void => {+ if (!choiceQuestion) {+ return+ }+ const choices = choiceQuestion.choices || []+ if (choiceQuestion.hasOpenChoice && choices.length > 0) {+ // Insert before the trailing open-ended choice so it stays last.+ const head = choices.slice(0, -1)+ const open = choices[choices.length - 1]+ commitChoices([...head, 'New option', open])+ return+ }+ commitChoices([...choices, 'New option'])+ }++ const reorderChoices = (from: number, to: number): void => {+ if (!choiceQuestion) {+ return+ }+ const choices = [...(choiceQuestion.choices || [])]+ // The open-ended option must always remain last — guard against accidental swaps.+ const lastIndex = choices.length - 1+ if (choiceQuestion.hasOpenChoice && (from === lastIndex || to === lastIndex)) {+ return+ }+ const [moved] = choices.splice(from, 1)+ choices.splice(to, 0, moved)+ commitChoices(choices)+ }++ const buttonTextDefault = question.type === SurveyQuestionType.Link ? 'Continue' : 'Submit'++ return (+ <form className="survey-form" name="surveyForm" onSubmit={(event) => event.preventDefault()}>+ <div className="survey-box" data-question-index={index}>+ <div className="question-container">+ <div>+ <InlineEditable+ as="h1"+ className="survey-question"+ value={question.question}+ onChange={(value) => updateField('question', value)}+ placeholder="Untitled question"+ ariaLabel="Question text"+ multiline+ data-attr={`canvas-question-${index}-text`}+ />+ {question.descriptionContentType === 'html' && question.description ? (+ // Keep HTML descriptions rendered (canvas v1 doesn't inline-edit HTML).+ <div+ className="survey-question-description"+ dangerouslySetInnerHTML={{ __html: sanitizeHTML(question.description) }}+ />+ ) : (+ <InlineEditable+ as="p"+ className="survey-question-description"+ value={question.description || ''}+ onChange={(value) => updateField('description', value)}+ placeholder="Add a description (optional)"+ ariaLabel="Question description"+ multiline+ data-attr={`canvas-question-${index}-description`}+ />+ )}+ </div>++ {question.type === SurveyQuestionType.Open ? (+ <textarea value="" placeholder="Respondent will type here…" readOnly aria-hidden />+ ) : null}++ {question.type === SurveyQuestionType.Link ? (+ <InlineEditable+ as="span"+ value={question.link || ''}+ onChange={(value) => updateField('link', value)}+ placeholder="https://example.com"+ ariaLabel="Destination URL"+ data-attr={`canvas-question-${index}-link`}+ />+ ) : null}++ {choiceQuestion && (+ <ChoicesEditor+ question={choiceQuestion}+ questionIndex={index}+ onChoiceChange={updateChoice}+ onChoiceDelete={deleteChoice}+ onChoiceAdd={addChoice}+ onChoiceReorder={reorderChoices}+ />+ )}++ {question.type === SurveyQuestionType.Rating ? (+ <RatingCanvas+ question={question as RatingSurveyQuestion}+ onLowerBoundChange={(value) => updateField('lowerBoundLabel', value)}+ onUpperBoundChange={(value) => updateField('upperBoundLabel', value)}+ />+ ) : null}++ <div className="bottom-section">+ <InlineEditable+ as="span"+ value={question.buttonText || ''}+ onChange={(value) => updateField('buttonText', value)}+ placeholder={buttonTextDefault}+ ariaLabel="Submit button label"+ className="form-submit"+ data-attr={`canvas-question-${index}-button-text`}+ />+ <KeyboardHints questionType={question.type} />+ </div>+ </div>+ </div>+ </form>+ )+}++// Keyboard hint chips next to the submit button. Mirrors the per-question+// hint set rendered by `posthog/templates/surveys/public_survey.html` so the+// canvas matches what respondents actually see.+function KeyboardHints({ questionType }: { questionType: SurveyQuestionType }): JSX.Element {+ const chips: { kbd: string; label: string }[] = [{ kbd: '\u21B5', label: 'submit' }]++ if (questionType === SurveyQuestionType.Open) {+ chips.push({ kbd: '\u21E7 \u21B5', label: 'new line' })+ } else if (questionType === SurveyQuestionType.SingleChoice) {+ chips.push({ kbd: '\u2191 \u2193', label: 'select' })+ } else if (questionType === SurveyQuestionType.MultipleChoice) {+ chips.push({ kbd: '\u2191 \u2193', label: 'select' })+ chips.push({ kbd: 'Space', label: 'toggle' })+ } else if (questionType === SurveyQuestionType.Rating) {+ chips.push({ kbd: '\u2190 \u2192', label: 'select' })+ }++ return (+ <span className="survey-keyhint" aria-hidden>+ {chips.map(({ kbd, label }) => (+ <span className="survey-keyhint-row" key={label}>+ <kbd className="survey-kbd">{kbd}</kbd>+ <span className="survey-keyhint-label">{label}</span>+ </span>+ ))}+ </span>+ )+}++function ChoicesEditor({+ question,+ questionIndex,+ onChoiceChange,+ onChoiceDelete,+ onChoiceAdd,+ onChoiceReorder,+}: {+ question: MultipleSurveyQuestion+ questionIndex: number+ onChoiceChange: (choiceIndex: number, value: string) => void+ onChoiceDelete: (choiceIndex: number) => void+ onChoiceAdd: () => void+ onChoiceReorder: (from: number, to: number) => void+}): JSX.Element {+ const choices = question.choices || []+ const lastIndex = choices.length - 1+ const choiceItemIds = choices.map((_, idx) => idx.toString())++ const handleDragEnd = ({ active, over }: DragEndEvent): void => {+ if (!over || active.id === over.id) {+ return+ }+ const from = choiceItemIds.indexOf(active.id.toString())+ const to = choiceItemIds.indexOf(over.id.toString())+ if (from < 0 || to < 0) {+ return+ }+ onChoiceReorder(from, to)+ }++ return (+ <fieldset>+ <legend className="sr-only">{question.question}</legend>+ <div className="multiple-choice-options">+ <DndContext onDragEnd={handleDragEnd}>+ <SortableContext items={choiceItemIds} strategy={verticalListSortingStrategy}>+ {choices.map((choice, choiceIndex) => {+ // When hasOpenChoice is enabled, the LAST choice renders with a ":" suffix and+ // an adjacent text input — mirroring what respondents see in the shipped survey.+ const isOpenChoice = !!question.hasOpenChoice && choiceIndex === lastIndex+ return (+ <ChoiceRow+ key={choiceIndex}+ id={choiceIndex.toString()}+ choice={choice}+ choiceIndex={choiceIndex}+ isOpenChoice={isOpenChoice}+ isCheckbox={question.type === SurveyQuestionType.MultipleChoice}+ canReorder={choices.length > 1 && !isOpenChoice}+ canDelete={choices.length > 1}+ questionIndex={questionIndex}+ onChoiceChange={onChoiceChange}+ onChoiceDelete={onChoiceDelete}+ />+ )+ })}+ </SortableContext>+ </DndContext>+ <button+ type="button"+ className="HostedSurveyCanvasAddChoice"+ onClick={onChoiceAdd}+ data-attr={`canvas-question-${questionIndex}-add-choice`}+ >+ <IconPlus />+ Add choice+ </button>+ </div>+ </fieldset>+ )+}++function ChoiceRow({+ id,+ choice,+ choiceIndex,+ isOpenChoice,+ isCheckbox,+ canReorder,+ canDelete,+ questionIndex,+ onChoiceChange,+ onChoiceDelete,+}: {+ id: string+ choice: string+ choiceIndex: number+ isOpenChoice: boolean+ isCheckbox: boolean+ canReorder: boolean+ canDelete: boolean+ questionIndex: number+ onChoiceChange: (choiceIndex: number, value: string) => void+ onChoiceDelete: (choiceIndex: number) => void+}): JSX.Element {+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({+ id,+ animateLayoutChanges: () => false,+ })++ return (+ <div+ ref={setNodeRef}+ {...attributes}+ className={`HostedSurveyCanvasChoice ${isDragging ? 'HostedSurveyCanvasChoice--dragging' : ''}`}+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ transform: CSS.Translate.toString(transform),+ transition,+ }}+ >+ <span+ className={`HostedSurveyCanvasChoice__grip ${canReorder ? '' : 'HostedSurveyCanvasChoice__grip--locked'}`}+ aria-label={canReorder ? `Reorder choice ${choiceIndex + 1}` : 'Open-ended choice stays last'}+ {...(canReorder ? listeners : {})}+ >+ <SortableDragIcon />+ </span>+ <label className={isOpenChoice ? 'choice-option-open' : undefined}>+ <div className="response-choice">+ <input+ type={isCheckbox ? 'checkbox' : 'radio'}+ checked={false}+ onChange={() => {}}+ aria-hidden+ tabIndex={-1}+ />+ <span className="HostedSurveyCanvasChoice__label">+ <InlineEditable+ value={choice}+ onChange={(value) => onChoiceChange(choiceIndex, value)}+ placeholder={`Choice ${choiceIndex + 1}`}+ ariaLabel={`Choice ${choiceIndex + 1}`}+ data-attr={`canvas-question-${questionIndex}-choice-${choiceIndex}`}+ />+ {isOpenChoice ? <span aria-hidden>:</span> : null}+ </span>+ </div>+ {isOpenChoice ? (+ <input+ type="text"+ placeholder="Respondent types their own answer…"+ readOnly+ aria-hidden+ tabIndex={-1}+ />+ ) : null}+ </label>+ <button+ type="button"+ className="HostedSurveyCanvasChoice__delete"+ aria-label={`Delete choice ${choiceIndex + 1}`}+ title={canDelete ? 'Delete choice' : 'A choice question needs at least one option'}+ disabled={!canDelete}+ onClick={() => onChoiceDelete(choiceIndex)}+ >+ <IconTrash />+ </button>+ </div>+ )+}++function RatingCanvas({+ question,+ onLowerBoundChange,+ onUpperBoundChange,+}: {+ question: RatingSurveyQuestion+ onLowerBoundChange: (value: string) => void+ onUpperBoundChange: (value: string) => void+}): JSX.Element {+ const scale = question.scale+ const length = scale === 10 ? 11 : scale+ return (+ <div className="rating-section">+ <div className={question.display === 'emoji' ? 'rating-options-emoji' : 'rating-options-number'}>+ {Array.from({ length }, (_, idx) => {+ const value = scale === 10 ? idx : idx + 1+ return (+ <button+ key={value}+ type="button"+ className={question.display === 'emoji' ? 'ratings-emoji' : 'ratings-number'}+ tabIndex={-1}+ aria-hidden+ >+ {question.display === 'emoji'+ ? RATING_EMOJI_PREVIEW[idx] || RATING_EMOJI_PREVIEW[3]+ : value}+ </button>+ )+ })}+ </div>+ <div className="rating-text">+ <InlineEditable+ value={question.lowerBoundLabel || ''}+ onChange={onLowerBoundChange}+ placeholder="Low end label"+ ariaLabel="Lower bound label"+ />+ <InlineEditable+ value={question.upperBoundLabel || ''}+ onChange={onUpperBoundChange}+ placeholder="High end label"+ ariaLabel="Upper bound label"+ />+ </div>+ </div>+ )+}++function ConfirmationCanvas({ survey }: { survey: Survey | NewSurvey }): JSX.Element {+ const { setSurveyValue } = useActions(surveyLogic)+ const appearance = survey.appearance ?? {}++ const updateAppearance = (patch: Partial<NonNullable<(Survey | NewSurvey)['appearance']>>): void => {+ setSurveyValue('appearance', { ...survey.appearance, ...patch })+ }++ return (+ <div className="thank-you-message">+ <InlineEditable+ as="h1"+ className="thank-you-message-header"+ value={appearance.thankYouMessageHeader || ''}+ onChange={(value) => updateAppearance({ thankYouMessageHeader: value })}+ placeholder="Thank you!"+ ariaLabel="Thank you header"+ />+ {appearance.thankYouMessageDescriptionContentType === 'html' && appearance.thankYouMessageDescription ? (+ // HTML descriptions keep their rendered form; v1 doesn't inline-edit raw HTML.+ <div+ className="thank-you-message-body"+ dangerouslySetInnerHTML={{ __html: sanitizeHTML(appearance.thankYouMessageDescription) }}+ />+ ) : (+ <InlineEditable+ as="p"+ className="thank-you-message-body"+ value={appearance.thankYouMessageDescription || ''}+ onChange={(value) => updateAppearance({ thankYouMessageDescription: value })}+ placeholder="Add a closing message (optional)"+ ariaLabel="Thank you description"+ multiline+ />+ )}+ {appearance.thankYouMessageCloseButtonText !== undefined ? (+ <div className="bottom-section">+ <InlineEditable+ value={appearance.thankYouMessageCloseButtonText || ''}+ onChange={(value) => updateAppearance({ thankYouMessageCloseButtonText: value })}+ placeholder="Close"+ ariaLabel="Close button label"+ className="form-submit"+ />+ </div>+ ) : null}+ </div>+ )+}diff --git a/frontend/src/scenes/surveys/hosted-canvas/HostedSurveySettingsPanel.tsx b/frontend/src/scenes/surveys/hosted-canvas/HostedSurveySettingsPanel.tsxnew file mode 100644index 000000000000..d9dd25c3f128--- /dev/null+++ b/frontend/src/scenes/surveys/hosted-canvas/HostedSurveySettingsPanel.tsx@@ -0,0 +1,305 @@+import { useActions, useValues } from 'kea'++import { IconPhone, IconPlusSmall, IconTrash } from '@posthog/icons'+import { LemonButton, LemonCheckbox, LemonDialog, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'++import { IconMonitor } from 'lib/lemon-ui/icons'+import { SCALE_OPTIONS, SURVEY_RATING_SCALE, SurveyQuestionLabel } from 'scenes/surveys/constants'+import { surveyLogic } from 'scenes/surveys/surveyLogic'+import { isThumbQuestion } from 'scenes/surveys/utils'++import {+ type MultipleSurveyQuestion,+ type RatingSurveyQuestion,+ type SurveyQuestion,+ SurveyQuestionType,+} from '~/types'++interface HostedSurveySettingsPanelProps {+ /** Active page in the canvas — used to pick the question to render settings for. */+ activePageIndex: number+ isConfirmation: boolean+ viewport: 'desktop' | 'mobile'+ onViewportChange: (viewport: 'desktop' | 'mobile') => void+ onRemoveConfirmation: () => void+}++const QUESTION_TYPE_OPTIONS = [+ { label: SurveyQuestionLabel[SurveyQuestionType.Open], value: SurveyQuestionType.Open },+ { label: 'Link / Notification', value: SurveyQuestionType.Link },+ { label: 'Rating', value: SurveyQuestionType.Rating },+ { label: 'Single choice', value: SurveyQuestionType.SingleChoice },+ { label: 'Multiple choice', value: SurveyQuestionType.MultipleChoice },+]++/**+ * Right-side settings panel for the hosted survey canvas. Houses everything that+ * doesn't fit inline on the canvas: type switching, scale config, choice options,+ * branching, viewport toggle, optional state.+ */+export function HostedSurveySettingsPanel({+ activePageIndex,+ isConfirmation,+ viewport,+ onViewportChange,+ onRemoveConfirmation,+}: HostedSurveySettingsPanelProps): JSX.Element {+ const { survey } = useValues(surveyLogic)+ const { setSurveyValue, setDefaultForQuestionType, resetBranchingForQuestion, setMultipleSurveyQuestion } =+ useActions(surveyLogic)++ const question = survey.questions[activePageIndex] as SurveyQuestion | undefined++ const handleQuestionTypeChange = (newType: SurveyQuestionType): void => {+ if (!question) {+ return+ }+ const isCurrentMultipleChoice =+ question.type === SurveyQuestionType.MultipleChoice || question.type === SurveyQuestionType.SingleChoice+ const isNewMultipleChoice =+ newType === SurveyQuestionType.MultipleChoice || newType === SurveyQuestionType.SingleChoice++ if (isCurrentMultipleChoice && isNewMultipleChoice) {+ setMultipleSurveyQuestion(activePageIndex, question as MultipleSurveyQuestion, newType)+ resetBranchingForQuestion(activePageIndex)+ return+ }++ const apply = (): void => {+ setDefaultForQuestionType(activePageIndex, question, newType)+ resetBranchingForQuestion(activePageIndex)+ }++ // Destructive transitions (e.g. choice → rating) lose configured choices — confirm first.+ if (isCurrentMultipleChoice && !isNewMultipleChoice) {+ LemonDialog.open({+ title: 'Changing question type',+ description: <p className="py-2">The choices you configured will be removed. Continue?</p>,+ primaryButton: { children: 'Continue', status: 'danger', onClick: apply },+ secondaryButton: { children: 'Cancel' },+ })+ return+ }++ apply()+ }++ // Per-question union typing makes a strict keyof updater painful — accept arbitrary+ // values here. Callers already constrain by question type.+ const updateQuestionField = (key: string, value: unknown): void => {+ if (!question) {+ return+ }+ const next = survey.questions.map((q, idx) => (idx === activePageIndex ? { ...q, [key]: value } : q))+ setSurveyValue('questions', next)+ }++ return (+ <aside className="flex min-w-0 flex-col gap-4 rounded border bg-surface-primary p-4">+ <SettingsSection+ title={isConfirmation ? 'End screen' : `Question ${activePageIndex + 1}`}+ subtitle={+ isConfirmation+ ? 'Shown after the final answer.'+ : question+ ? SurveyQuestionLabel[question.type]+ : 'No question selected'+ }+ actions={+ isConfirmation ? (+ <LemonButton+ type="tertiary"+ size="small"+ status="danger"+ icon={<IconTrash />}+ onClick={onRemoveConfirmation}+ tooltip="Remove the end screen"+ />+ ) : null+ }+ />++ {!isConfirmation && question ? (+ <>+ <LabelledControl label="Type">+ <LemonSelect+ fullWidth+ value={question.type}+ options={QUESTION_TYPE_OPTIONS}+ onSelect={(value) => handleQuestionTypeChange(value)}+ data-attr={`canvas-question-${activePageIndex}-type`}+ />+ </LabelledControl>++ <LemonCheckbox+ label="Optional"+ checked={!!question.optional}+ onChange={(checked) => updateQuestionField('optional', checked)}+ />++ {question.type === SurveyQuestionType.Rating ? (+ <RatingSettings+ question={question as RatingSurveyQuestion}+ onDisplayChange={(value) => {+ const next = survey.questions.map((q, idx) =>+ idx === activePageIndex+ ? {+ ...q,+ display: value,+ scale: SURVEY_RATING_SCALE.LIKERT_5_POINT,+ }+ : q+ )+ setSurveyValue('questions', next)+ setSurveyValue('appearance', {+ ...survey.appearance,+ ratingButtonColor: value === 'emoji' ? '#939393' : 'white',+ })+ resetBranchingForQuestion(activePageIndex)+ }}+ onScaleChange={(value) => {+ updateQuestionField('scale', value)+ resetBranchingForQuestion(activePageIndex)+ }}+ onIsNpsChange={(checked) => updateQuestionField('isNpsQuestion', checked)}+ />+ ) : null}++ {(question.type === SurveyQuestionType.SingleChoice ||+ question.type === SurveyQuestionType.MultipleChoice) && (+ <OpenChoiceControl+ question={question as MultipleSurveyQuestion}+ onAdd={() => {+ const choices = (question as MultipleSurveyQuestion).choices || []+ const next = survey.questions.map((q, idx) =>+ idx === activePageIndex+ ? { ...q, choices: [...choices, 'Other'], hasOpenChoice: true }+ : q+ )+ setSurveyValue('questions', next)+ }}+ onRemove={() => {+ const choices = (question as MultipleSurveyQuestion).choices || []+ // Strip the trailing open-ended option and clear the flag.+ const next = survey.questions.map((q, idx) =>+ idx === activePageIndex+ ? { ...q, choices: choices.slice(0, -1), hasOpenChoice: false }+ : q+ )+ setSurveyValue('questions', next)+ }}+ />+ )}+ </>+ ) : null}++ <div className="border-t pt-3">+ <SettingsSection title="Preview" subtitle="Switch between desktop and mobile framing." />+ <LemonSegmentedButton+ size="small"+ value={viewport}+ onChange={onViewportChange}+ options={[+ { label: <IconMonitor />, value: 'desktop', tooltip: 'Desktop' },+ { label: <IconPhone />, value: 'mobile', tooltip: 'Mobile' },+ ]}+ fullWidth+ />+ </div>+ </aside>+ )+}++function SettingsSection({+ title,+ subtitle,+ actions,+}: {+ title: string+ subtitle?: string+ actions?: React.ReactNode+}): JSX.Element {+ return (+ <div className="flex items-start justify-between gap-2">+ <div>+ <h3 className="mb-0 text-sm font-semibold uppercase tracking-wide text-secondary">{title}</h3>+ {subtitle ? <p className="mb-0 text-xs text-muted">{subtitle}</p> : null}+ </div>+ {actions}+ </div>+ )+}++function LabelledControl({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {+ return (+ <label className="flex flex-col gap-1 text-xs font-medium text-secondary">+ {label}+ {children}+ </label>+ )+}++function RatingSettings({+ question,+ onDisplayChange,+ onScaleChange,+ onIsNpsChange,+}: {+ question: RatingSurveyQuestion+ onDisplayChange: (display: 'number' | 'emoji') => void+ onScaleChange: (scale: number) => void+ onIsNpsChange: (checked: boolean) => void+}): JSX.Element {+ const isNpsCheckboxApplicable = question.scale === SURVEY_RATING_SCALE.NPS_10_POINT+ return (+ <>+ <LabelledControl label="Display">+ <LemonSelect+ fullWidth+ value={question.display}+ options={[+ { label: 'Number', value: 'number' },+ { label: 'Emoji', value: 'emoji' },+ ]}+ onChange={(value) => onDisplayChange(value as 'number' | 'emoji')}+ />+ </LabelledControl>+ <LabelledControl label="Scale">+ <LemonSelect+ fullWidth+ value={question.scale}+ options={question.display === 'emoji' ? SCALE_OPTIONS.EMOJI : SCALE_OPTIONS.NUMBER}+ onChange={(value) => onScaleChange(value as number)}+ />+ </LabelledControl>+ {!isThumbQuestion(question) && isNpsCheckboxApplicable ? (+ <LemonCheckbox+ label="Treat as NPS"+ info="If checked, we'll calculate and display NPS on the survey results page."+ checked={question.isNpsQuestion !== false}+ onChange={onIsNpsChange}+ />+ ) : null}+ </>+ )+}++function OpenChoiceControl({+ question,+ onAdd,+ onRemove,+}: {+ question: MultipleSurveyQuestion+ onAdd: () => void+ onRemove: () => void+}): JSX.Element {+ return question.hasOpenChoice ? (+ <LemonButton type="tertiary" size="small" status="danger" icon={<IconTrash />} onClick={onRemove}>+ Remove open-ended choice+ </LemonButton>+ ) : (+ <LemonButton type="secondary" size="small" icon={<IconPlusSmall />} onClick={onAdd}>+ Add open-ended choice+ </LemonButton>+ )+}diff --git a/frontend/src/scenes/surveys/hosted-canvas/InlineEditable.tsx b/frontend/src/scenes/surveys/hosted-canvas/InlineEditable.tsxnew file mode 100644index 000000000000..8b6f7d08fa2f--- /dev/null+++ b/frontend/src/scenes/surveys/hosted-canvas/InlineEditable.tsx@@ -0,0 +1,151 @@+import clsx from 'clsx'+import { useEffect, useRef, useState } from 'react'++type DisplayTag = 'span' | 'div' | 'p' | 'h1' | 'h2'++interface InlineEditableProps {+ value: string+ onChange: (value: string) => void+ placeholder?: string+ multiline?: boolean+ /** Element used to render the non-editing display. Input mimics its styling. */+ as?: DisplayTag+ /** Class applied to both the display element and the editing input. */+ className?: string+ /** ARIA label for screen readers. */+ ariaLabel?: string+ /** Disable editing (e.g. when the survey is read-only). */+ disabled?: boolean+ /** Show invalid state — red outline plus tooltip-friendly title. */+ invalid?: boolean+ invalidReason?: string+ /** Optional data-attr forwarded to both display and input. */+ 'data-attr'?: string+}++/**+ * Click-to-edit text primitive used by the hosted survey canvas. The display+ * and the editing input share the same className so the visual transition is+ * minimal — the canvas stays WYSIWYG even while editing.+ */+export function InlineEditable({+ value,+ onChange,+ placeholder,+ multiline = false,+ as = 'span',+ className,+ ariaLabel,+ disabled = false,+ invalid = false,+ invalidReason,+ 'data-attr': dataAttr,+}: InlineEditableProps): JSX.Element {+ const [editing, setEditing] = useState(false)+ const [draft, setDraft] = useState(value)+ const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement | null>(null)++ useEffect(() => {+ if (!editing) {+ setDraft(value)+ }+ }, [value, editing])++ useEffect(() => {+ if (editing && inputRef.current) {+ inputRef.current.focus()+ inputRef.current.select()+ }+ }, [editing])++ const commit = (): void => {+ if (draft !== value) {+ onChange(draft)+ }+ setEditing(false)+ }++ const cancel = (): void => {+ setDraft(value)+ setEditing(false)+ }++ const sharedClass = clsx(+ 'inline-editable',+ invalid && 'inline-editable--invalid',+ editing && 'inline-editable--editing',+ className+ )++ if (editing && !disabled) {+ const handleKey = (event: React.KeyboardEvent): void => {+ if (event.key === 'Escape') {+ event.preventDefault()+ cancel()+ } else if (event.key === 'Enter' && (!multiline || event.metaKey || event.ctrlKey)) {+ event.preventDefault()+ commit()+ }+ }++ return multiline ? (+ <textarea+ ref={inputRef as React.RefObject<HTMLTextAreaElement>}+ value={draft}+ placeholder={placeholder}+ aria-label={ariaLabel}+ onChange={(event) => setDraft(event.target.value)}+ onBlur={commit}+ onKeyDown={handleKey}+ className={sharedClass}+ data-attr={dataAttr}+ // 1 row is the floor — `field-sizing: content` + scrollHeight+ // auto-grow take over from there. Without this the browser+ // defaults to 2 visible rows, which already feels too tall+ // for a one-line question title.+ rows={1}+ />+ ) : (+ <input+ ref={inputRef as React.RefObject<HTMLInputElement>}+ type="text"+ value={draft}+ placeholder={placeholder}+ aria-label={ariaLabel}+ onChange={(event) => setDraft(event.target.value)}+ onBlur={commit}+ onKeyDown={handleKey}+ className={sharedClass}+ data-attr={dataAttr}+ />+ )+ }++ const DisplayTag = as+ const displayValue = value || placeholder || ''+ const isPlaceholder = !value++ return (+ <DisplayTag+ role={disabled ? undefined : 'button'}+ tabIndex={disabled ? undefined : 0}+ aria-label={ariaLabel}+ title={invalid ? invalidReason : undefined}+ onClick={disabled ? undefined : () => setEditing(true)}+ onKeyDown={+ disabled+ ? undefined+ : (event: React.KeyboardEvent) => {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault()+ setEditing(true)+ }+ }+ }+ className={clsx(sharedClass, isPlaceholder && 'inline-editable--placeholder')}+ data-attr={dataAttr}+ >+ {displayValue}+ </DisplayTag>+ )+}