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.

11.1 KB
Raw Blame
import { useActions, useValues } from 'kea'
import { ReactNode } from 'react'

import { IconDownload } from '@posthog/icons'
import { LemonButton, LemonMenu, LemonSelect, Link } from '@posthog/lemon-ui'

import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'
import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
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,
} from 'scenes/surveys/utils'

import {
    AccessControlLevel,
    AccessControlResourceType,
    ExporterFormat,
    Survey,
    SurveySchedule as SurveyScheduleEnum,
    SurveyType,
} from '~/types'

import { SurveyConditionsList } from '../components/SurveyConditions'
import { CopySurveyLink } from '../CopySurveyLink'

// ============================================================================
// Panel Section - Wrapper for consistent panel styling
// ============================================================================

interface PanelSectionProps {
    title: string
    description?: string
    children: ReactNode
}

function PanelSection({ title, description, children }: PanelSectionProps): JSX.Element {
    return (
        <div className="flex flex-col gap-3">
            <div>
                <div className="text-xs font-semibold uppercase tracking-wide">{title}</div>
                {description && <p className="text-xs text-muted m-0 mt-1">{description}</p>}
            </div>
            {children}
        </div>
    )
}

function formatSurveySchedule(survey: Survey): string {
    if (survey.schedule === SurveyScheduleEnum.Recurring && survey.iteration_count && survey.iteration_frequency_days) {
        return `Show up to ${survey.iteration_count} ${pluralize(
            survey.iteration_count,
            'time',
            'times',
            false
        )} total, once every ${pluralize(survey.iteration_frequency_days, 'day')}`
    }

    if (survey.schedule === SurveyScheduleEnum.Always) {
        return 'Always'
    }

    return 'Once'
}

// ============================================================================
// Panel Components
// ============================================================================

export function SurveyDetailsPanel(): JSX.Element {
    const { survey, selectedPageIndex, hasTargetingSet } = useValues(surveyLogic)
    const { setSelectedPageIndex } = useActions(surveyLogic)
    const isNonApiSurvey = survey.type !== SurveyType.API
    const statusLabel = !survey.start_date ? 'Draft' : survey.end_date ? 'Complete' : 'Running'
    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">
            {/* Preview */}
            {isNonApiSurvey && (
                <PanelSection title="Preview">
                    <div className="flex flex-col gap-3">
                        <div className="flex justify-center">
                            <SurveyAppearancePreview
                                survey={survey as Survey}
                                previewPageIndex={effectivePageIndex}
                                onPreviewSubmit={(response) => {
                                    const nextPageIndex = getNextPreviewPageIndex(survey, effectivePageIndex, response)
                                    if (nextPageIndex !== null) {
                                        setSelectedPageIndex(nextPageIndex)
                                    }
                                }}
                            />
                        </div>
                        <LemonSelect
                            size="xsmall"
                            fullWidth
                            value={effectivePageIndex}
                            onChange={(pageIndex) => setSelectedPageIndex(pageIndex)}
                            options={[
                                ...getIntroScreenPageOptions(survey),
                                ...survey.questions.map((question, index) => ({
                                    label: `${index + 1}. ${question.question ?? ''}`,
                                    value: index,
                                })),
                                ...(survey.appearance?.displayThankYouMessage
                                    ? [{ label: 'Thank you message', value: survey.questions.length }]
                                    : []),
                            ]}
                        />
                    </div>
                </PanelSection>
            )}

            {/* Survey info */}
            <PanelSection title="At a glance">
                <div className="flex flex-col gap-1.5 text-sm">
                    <div className="flex justify-between">
                        <span className="text-muted">Status</span>
                        <span>{statusLabel}</span>
                    </div>
                    <div className="flex justify-between">
                        <span className="text-muted">Type</span>
                        <span>{SURVEY_TYPE_LABEL_MAP[survey.type]}</span>
                    </div>
                    <div className="flex justify-between">
                        <span className="text-muted">Schedule</span>
                        <span>{formatSurveySchedule(survey as Survey)}</span>
                    </div>
                    {scheduleInfo && (
                        <div className="flex justify-between">
                            <span className="text-muted">Auto-closes</span>
                            <span>
                                {scheduleInfo.autoCloseDate
                                    ? scheduleInfo.autoCloseDate.isBefore(dayjs())
                                        ? 'Soon'
                                        : scheduleInfo.autoCloseDate.format('MMMM D, YYYY')
                                    : `After ${pluralize(scheduleInfo.totalDurationDays, 'day')}`}
                            </span>
                        </div>
                    )}
                    <div className="flex justify-between">
                        <span className="text-muted">Audience</span>
                        <span>{hasTargetingSet ? 'Targeted' : 'All users'}</span>
                    </div>
                    {survey.start_date && (
                        <div className="flex justify-between">
                            <span className="text-muted">Started</span>
                            <TZLabel time={survey.start_date} />
                        </div>
                    )}
                    {survey.end_date && (
                        <div className="flex justify-between">
                            <span className="text-muted">Ended</span>
                            <TZLabel time={survey.end_date} />
                        </div>
                    )}
                    {collectionLimitSummary && (
                        <div className="flex justify-between">
                            <span className="text-muted">{collectionLimitSummary.label}</span>
                            <span>{collectionLimitSummary.value}</span>
                        </div>
                    )}
                    {survey.type === SurveyType.ExternalSurvey && (
                        <div className="flex flex-col gap-2 pt-1">
                            <span className="text-muted text-xs">Share link</span>
                            <CopySurveyLink
                                surveyId={survey.id}
                                enableIframeEmbedding={survey.enable_iframe_embedding ?? false}
                            />
                        </div>
                    )}
                    {survey.type === SurveyType.API && (
                        <div className="flex justify-between">
                            <span className="text-muted">API docs</span>
                            <Link to="https://posthog.com/docs/surveys/implementing-custom-surveys" target="_blank">
                                View docs
                            </Link>
                        </div>
                    )}
                </div>
            </PanelSection>

            {conditionsSummary.length > 0 && (
                <PanelSection title="Display conditions">
                    <SurveyConditionsList conditions={conditionsSummary} />
                </PanelSection>
            )}
        </div>
    )
}

export function SurveyExportPanel(): JSX.Element {
    const { survey, responsesExportQuery } = useValues(surveyLogic)
    const { startExport } = useActions(exportsLogic)

    // Creating an export requires editor access to the export resource.
    const exportAccessControlDisabledReason = getAccessControlDisabledReason(
        AccessControlResourceType.Export,
        AccessControlLevel.Editor
    )

    const handleExport = (format: ExporterFormat): void => {
        if (!responsesExportQuery) {
            return
        }
        startExport({
            export_format: format,
            export_context: {
                source: responsesExportQuery,
                columns: responsesExportQuery.columns,
                filename: `survey-${survey.name}-responses`,
            },
        })
    }

    return (
        <PanelSection title="Export" description="Download survey responses">
            {responsesExportQuery ? (
                <LemonMenu
                    items={[
                        {
                            label: 'Export as CSV',
                            onClick: () => handleExport(ExporterFormat.CSV),
                            disabledReason: exportAccessControlDisabledReason ?? undefined,
                        },
                        {
                            label: 'Export as Excel',
                            onClick: () => handleExport(ExporterFormat.XLSX),
                            disabledReason: exportAccessControlDisabledReason ?? undefined,
                        },
                    ]}
                >
                    <LemonButton
                        type="secondary"
                        size="small"
                        fullWidth
                        icon={<IconDownload />}
                        data-attr="export-survey-responses"
                    >
                        Export responses
                    </LemonButton>
                </LemonMenu>
            ) : (
                <p className="text-xs text-muted m-0">No responses to export yet.</p>
            )}
        </PanelSection>
    )
}