Skip to content

: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.

2.2 KB
Raw Blame
import { renderFeedbackWidgetPreview, renderSurveysPreview } from 'posthog-js/dist/surveys-preview'
import { useEffect, useMemo, useRef } from 'react'

import { sanitizeSurvey } from 'scenes/surveys/utils'

import { Survey } from '~/types'

import { NewSurvey } from './constants'

interface Props {
    survey: Survey | NewSurvey
    previewPageIndex: number
    onPreviewSubmit?: (res: string | string[] | number | null) => void
    onPreviewBack?: () => void
    positionStyles?: React.CSSProperties
}

const DEFAULT_POSITION_STYLES: React.CSSProperties = {
    position: 'relative',
    left: 'unset',
    right: 'unset',
    top: 'unset',
    bottom: 'unset',
    transform: 'unset',
    width: 'var(--ph-survey-max-width)',
    maxWidth: '100%',
    minWidth: 'min(300px, 100%)',
    boxSizing: 'border-box',
}

export function SurveyAppearancePreview({
    survey,
    previewPageIndex,
    onPreviewSubmit = () => {},
    onPreviewBack = () => {},
    positionStyles = DEFAULT_POSITION_STYLES,
}: Props): JSX.Element {
    const surveyPreviewRef = useRef<HTMLDivElement>(null)
    const feedbackWidgetPreviewRef = useRef<HTMLDivElement>(null)

    const sanitizedSurvey = useMemo(
        () =>
            sanitizeSurvey({
                ...survey,
                appearance: {
                    ...survey.appearance,
                    zIndex: '1',
                },
            }),
        [survey]
    )

    useEffect(() => {
        if (surveyPreviewRef.current) {
            renderSurveysPreview({
                survey: sanitizedSurvey,
                parentElement: surveyPreviewRef.current,
                previewPageIndex,
                onPreviewSubmit,
                onPreviewBack,
                positionStyles,
            })
        }

        if (feedbackWidgetPreviewRef.current) {
            renderFeedbackWidgetPreview({
                survey: sanitizedSurvey,
                root: feedbackWidgetPreviewRef.current,
            })
        }
    }, [survey, previewPageIndex, onPreviewSubmit, onPreviewBack, positionStyles]) // oxlint-disable-line react-hooks/exhaustive-deps

    return <div ref={surveyPreviewRef} className="flex w-full min-w-0 justify-center" />
}