: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(toolbar): allow quick survey creation (#52668)
Fernando Gomes625172b9ad9d
diff --git a/frontend/src/toolbar/bar/Toolbar.tsx b/frontend/src/toolbar/bar/Toolbar.tsxindex 808d27136a39..6007634295f8 100644--- a/frontend/src/toolbar/bar/Toolbar.tsx+++ b/frontend/src/toolbar/bar/Toolbar.tsx@@ -50,6 +50,8 @@ import { ProductToursToolbarMenu } from '~/toolbar/product-tours/ProductToursTooimport { screenshotUploadLogic } from '~/toolbar/screenshot-upload/screenshotUploadLogic'import { ScreenshotUploadModal } from '~/toolbar/screenshot-upload/ScreenshotUploadModal'import { HeatmapToolbarMenu } from '~/toolbar/stats/HeatmapToolbarMenu'+import { SurveySidebar } from '~/toolbar/surveys/SurveySidebar'+import { surveysToolbarLogic } from '~/toolbar/surveys/surveysToolbarLogic'import { SurveysToolbarMenu } from '~/toolbar/surveys/SurveysToolbarMenu'import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'import { useToolbarFeatureFlag } from '~/toolbar/toolbarPosthogJS'@@ -392,6 +394,7 @@ export function Toolbar(): JSX.Element | null {const { authenticate, openUiHostConfigModal, closeUiHostConfigModal, closeAuthConfirmModal } =useActions(toolbarConfigLogic)const { selectedTourId, isPreviewing } = useValues(productToursLogic)+ const { isCreating: isSurveyCreating } = useValues(surveysToolbarLogic)const showExperimentsFlag = useToolbarFeatureFlag('web-experiments')const showExperiments = inStorybook() || inStorybookTestRunner() || showExperimentsFlag@@ -436,11 +439,12 @@ export function Toolbar(): JSX.Element | null {return null}- const showSidebar = selectedTourId !== null && !isPreviewing+ const showToursSidebar = selectedTourId !== null && !isPreviewingreturn (<>- {showSidebar && <ProductToursSidebar />}+ {showToursSidebar && <ProductToursSidebar />}+ {isSurveyCreating && <SurveySidebar />}<ToolbarInfoMenu /><divref={ref}diff --git a/frontend/src/toolbar/surveys/SurveyListView.tsx b/frontend/src/toolbar/surveys/SurveyListView.tsxnew file mode 100644index 000000000000..a73117d8f760--- /dev/null+++ b/frontend/src/toolbar/surveys/SurveyListView.tsx@@ -0,0 +1,78 @@+import { useValues, useActions } from 'kea'++import { IconPlus } from '@posthog/icons'+import { LemonInput, LemonButton, Spinner } from '@posthog/lemon-ui'++import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'++import { Survey } from '~/types'++import { ToolbarMenu } from '../bar/ToolbarMenu'+import { SurveyRow } from './SurveyRow'+import { surveysToolbarLogic } from './surveysToolbarLogic'++export function SurveyListView(): JSX.Element {+ const { searchTerm, allSurveys, allSurveysLoading, hasMoreSurveys } = useValues(surveysToolbarLogic)+ const { setSearchTerm, loadSurveys, loadMoreSurveys, startQuickCreate } = useActions(surveysToolbarLogic)++ useOnMountEffect(() => {+ loadSurveys()+ })++ return (+ <ToolbarMenu>+ <ToolbarMenu.Header>+ <div className="flex gap-1 items-center w-full">+ <LemonInput+ autoFocus+ placeholder="Search surveys"+ fullWidth+ type="search"+ size="small"+ value={searchTerm}+ onChange={(s) => setSearchTerm(s)}+ />+ <LemonButton+ size="small"+ type="primary"+ icon={<IconPlus />}+ onClick={startQuickCreate}+ tooltip="Quick create survey"+ className="flex-shrink-0"+ />+ </div>+ </ToolbarMenu.Header>+ <ToolbarMenu.Body>+ <div className="mt-1">+ {allSurveysLoading && allSurveys.length === 0 ? (+ <div className="flex justify-center py-4">+ <Spinner className="text-2xl" />+ </div>+ ) : allSurveys.length > 0 ? (+ <>+ {allSurveys.map((survey: Survey) => (+ <SurveyRow key={survey.id} survey={survey} />+ ))}+ {hasMoreSurveys && (+ <div className="flex justify-center py-2">+ <LemonButton+ size="xsmall"+ type="secondary"+ loading={allSurveysLoading}+ onClick={loadMoreSurveys}+ >+ Load more+ </LemonButton>+ </div>+ )}+ </>+ ) : (+ <div className="text-muted text-sm text-center py-4">+ {searchTerm ? 'No matching surveys found.' : 'No surveys found in this project.'}+ </div>+ )}+ </div>+ </ToolbarMenu.Body>+ </ToolbarMenu>+ )+}diff --git a/frontend/src/toolbar/surveys/SurveyLivePreview.tsx b/frontend/src/toolbar/surveys/SurveyLivePreview.tsxnew file mode 100644index 000000000000..cdfbd7c83d5d--- /dev/null+++ b/frontend/src/toolbar/surveys/SurveyLivePreview.tsx@@ -0,0 +1,102 @@+import { useValues } from 'kea'+import { renderSurveysPreview } from 'posthog-js/dist/surveys-preview'+import { useEffect, useMemo, useRef } from 'react'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import { SIDEBAR_WIDTH } from './constants'+import { surveysToolbarLogic, SURVEY_PREVIEW_Z_INDEX } from './surveysToolbarLogic'++const PREVIEW_CONTAINER_PREFIX = '__posthog_toolbar_survey_preview__'+const RENDER_DEBOUNCE_MS = 150++const PREVIEW_BASE_STYLES: React.CSSProperties = {+ position: 'fixed',+ zIndex: SURVEY_PREVIEW_Z_INDEX,+ bottom: 0,+}++/**+ * Renders a live survey preview directly on the page (outside the shadow DOM)+ * as the user fills in the quick-create form. The survey appears in its natural+ * position (bottom-right) exactly as end users would see it.+ *+ * Failure modes addressed:+ * - Container ID is suffixed per-mount so two toolbar instances don't collide.+ * - Renders are debounced so a fast typist doesn't trigger Preact diffs on every+ * keystroke and (potentially) leak listeners through the upstream renderer.+ * - On viewports too narrow to fit the preview alongside the sidebar, the+ * preview falls back to a centered position so it isn't clipped off-screen.+ * - If `renderSurveysPreview` throws, surface a one-time toast — silently+ * no-op'ing makes the user think they typed something invalid.+ */+export function SurveyLivePreview(): JSX.Element | null {+ const { previewSurvey, isCreating } = useValues(surveysToolbarLogic)+ const containerRef = useRef<HTMLDivElement | null>(null)+ const renderTimerRef = useRef<number | null>(null)+ const renderErrorWarnedRef = useRef(false)+ // One ID per mount to avoid collisions if a stranded container leaks.+ const containerId = useMemo(() => `${PREVIEW_CONTAINER_PREFIX}${Math.random().toString(36).slice(2)}`, [])++ // Create/destroy the preview container on the real page (outside shadow DOM)+ useEffect(() => {+ if (!isCreating) {+ return+ }+ const container = document.createElement('div')+ container.id = containerId+ document.body.appendChild(container)+ containerRef.current = container++ return () => {+ container.remove()+ containerRef.current = null+ renderErrorWarnedRef.current = false+ }+ }, [isCreating, containerId])++ // Debounce re-renders to ~150ms so per-keystroke typing doesn't spin the+ // upstream renderer.+ useEffect(() => {+ const container = containerRef.current+ if (!container || !previewSurvey) {+ return+ }+ if (renderTimerRef.current !== null) {+ window.clearTimeout(renderTimerRef.current)+ }+ renderTimerRef.current = window.setTimeout(() => {+ renderTimerRef.current = null+ try {+ // Position: align with the sidebar when there's room, otherwise+ // center bottom so it isn't clipped on narrow viewports.+ const fitsBesideSidebar = window.innerWidth > SIDEBAR_WIDTH + 320+ const positionStyles: React.CSSProperties = fitsBesideSidebar+ ? { ...PREVIEW_BASE_STYLES, right: SIDEBAR_WIDTH + 16 }+ : { ...PREVIEW_BASE_STYLES, left: '50%', transform: 'translateX(-50%)' }+ renderSurveysPreview({+ survey: previewSurvey,+ parentElement: container,+ previewPageIndex: 0,+ positionStyles,+ })+ } catch (e) {+ // eslint-disable-next-line no-console+ console.warn('[Toolbar] Survey preview render failed:', e)+ if (!renderErrorWarnedRef.current) {+ renderErrorWarnedRef.current = true+ lemonToast.warning("Survey preview couldn't render. Your save will still work.")+ }+ }+ }, RENDER_DEBOUNCE_MS)++ return () => {+ if (renderTimerRef.current !== null) {+ window.clearTimeout(renderTimerRef.current)+ renderTimerRef.current = null+ }+ }+ }, [previewSurvey])++ return null+}diff --git a/frontend/src/toolbar/surveys/SurveyRow.tsx b/frontend/src/toolbar/surveys/SurveyRow.tsxnew file mode 100644index 000000000000..5f2d4c0b63b4--- /dev/null+++ b/frontend/src/toolbar/surveys/SurveyRow.tsx@@ -0,0 +1,65 @@+import { useActions, useValues } from 'kea'++import { IconPencil } from '@posthog/icons'+import { LemonBadge } from '@posthog/lemon-ui'++import { IconOpenInNew } from 'lib/lemon-ui/icons'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { Link } from 'lib/lemon-ui/Link'+import { urls } from 'scenes/urls'++import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'+import { joinWithUiHost } from '~/toolbar/utils'+import { Survey } from '~/types'++import { STATUS_COLORS, SURVEY_TYPE_LABELS } from './constants'+import { getSurveyStatus, isQuickEditable, surveysToolbarLogic } from './surveysToolbarLogic'++export function SurveyRow({ survey }: { survey: Survey }): JSX.Element {+ const { uiHost } = useValues(toolbarConfigLogic)+ const { startQuickEdit } = useActions(surveysToolbarLogic)+ const status = getSurveyStatus(survey)+ const typeLabel = SURVEY_TYPE_LABELS[survey.type] ?? survey.type+ const canEdit = isQuickEditable(survey)++ return (+ <div className="flex items-center gap-2 py-1.5 px-1 -mx-1 rounded hover:bg-fill-primary-hover">+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-1.5">+ <Link+ className="font-medium truncate"+ to={joinWithUiHost(uiHost, urls.survey(survey.id))}+ subtle+ target="_blank"+ >+ {survey.name}+ <IconOpenInNew className="ml-0.5" />+ </Link>+ </div>+ <div className="flex items-center gap-1.5 mt-0.5">+ <span className="text-xs text-muted">{typeLabel}</span>+ <span className="text-xs text-muted">·</span>+ <LemonBadge size="small" status={STATUS_COLORS[status] ?? 'muted'} content={status} />+ {survey.questions.length > 0 && (+ <>+ <span className="text-xs text-muted">·</span>+ <span className="text-xs text-muted">+ {survey.questions.length} {survey.questions.length === 1 ? 'question' : 'questions'}+ </span>+ </>+ )}+ </div>+ </div>+ {canEdit && (+ <LemonButton+ size="xsmall"+ type="secondary"+ icon={<IconPencil />}+ onClick={() => startQuickEdit(survey)}+ tooltip="Edit in toolbar"+ className="shrink-0"+ />+ )}+ </div>+ )+}diff --git a/frontend/src/toolbar/surveys/SurveySidebar.tsx b/frontend/src/toolbar/surveys/SurveySidebar.tsxnew file mode 100644index 000000000000..dd0ec0f0ae4b--- /dev/null+++ b/frontend/src/toolbar/surveys/SurveySidebar.tsx@@ -0,0 +1,584 @@+import { useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { IconArchive, IconEllipsis, IconExternal, IconPlus, IconRocket, IconTrash, IconX } from '@posthog/icons'+import { LemonButton, LemonSegmentedButton } from '@posthog/lemon-ui'++import { LemonInput } from 'lib/lemon-ui/LemonInput'+import { LemonMenu } from 'lib/lemon-ui/LemonMenu'+import { LemonRadio } from 'lib/lemon-ui/LemonRadio'+import { LemonSelect } from 'lib/lemon-ui/LemonSelect'+import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'+import { Link } from 'lib/lemon-ui/Link'+import { urls } from 'scenes/urls'++import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'+import { joinWithUiHost } from '~/toolbar/utils'+import { SurveyMatchType } from '~/types'++import { SIDEBAR_WIDTH } from './constants'+import { SurveyLivePreview } from './SurveyLivePreview'+import {+ clampDelaySeconds,+ FREQUENCY_OPTIONS,+ getSurveyStatus,+ type QuickSurveyQuestionType,+ SURVEY_CHOICE_MAX_LENGTH,+ SURVEY_DELAY_MAX_SECONDS,+ SURVEY_NAME_MAX_LENGTH,+ SURVEY_QUESTION_MAX_LENGTH,+ SURVEY_QUICK_FORM_MAX_CHOICES,+ surveysToolbarLogic,+} from './surveysToolbarLogic'++const SIDEBAR_TRANSITION_MS = 200+const SIDEBAR_Z_INDEX = 2147483019++const QUESTION_TYPE_OPTIONS = [+ { value: 'open' as const, label: 'Open text' },+ { value: 'rating' as const, label: 'Rating scale' },+ { value: 'single_choice' as const, label: 'Single choice' },+]++const URL_MATCH_TYPE_OPTIONS: { value: SurveyMatchType; label: string }[] = [+ { value: SurveyMatchType.Exact, label: 'Exact' },+ { value: SurveyMatchType.Contains, label: 'Contains' },+ { value: SurveyMatchType.Regex, label: 'Regex' },+]++function QuestionSection(): JSX.Element {+ const { quickForm } = useValues(surveysToolbarLogic)+ const { setFormField } = useActions(surveysToolbarLogic)++ return (+ <section>+ <h3 className="text-xs font-semibold text-muted-3000 uppercase tracking-wide mb-3">Question</h3>+ <div className="space-y-3">+ <div>+ <label className="text-xs font-medium text-muted mb-0.5 block">Survey name</label>+ <LemonInput+ placeholder="e.g. Feedback on checkout"+ fullWidth+ size="small"+ maxLength={SURVEY_NAME_MAX_LENGTH}+ value={quickForm.name}+ onChange={(v) => setFormField('name', v)}+ />+ </div>++ <div>+ <label className="text-xs font-medium text-muted mb-0.5 block">Question type</label>+ <LemonSelect+ fullWidth+ size="small"+ options={QUESTION_TYPE_OPTIONS}+ value={quickForm.questionType}+ onChange={(v) => setFormField('questionType', v as QuickSurveyQuestionType)}+ />+ </div>++ <div>+ <label className="text-xs font-medium text-muted mb-0.5 block">Question text</label>+ <LemonTextArea+ placeholder="What would you like to ask?"+ value={quickForm.questionText}+ onChange={(v) => setFormField('questionText', v.slice(0, SURVEY_QUESTION_MAX_LENGTH))}+ minRows={2}+ maxRows={4}+ />+ </div>++ {quickForm.questionType === 'rating' && (+ <>+ <div>+ <label className="text-xs font-medium text-muted mb-0.5 block">Scale</label>+ <LemonSelect+ fullWidth+ size="small"+ options={[+ { value: 5, label: '1–5' },+ { value: 10, label: '1–10 (NPS)' },+ ]}+ value={quickForm.ratingScale}+ onChange={(v) => setFormField('ratingScale', v)}+ />+ </div>+ <div className="flex gap-2">+ <div className="flex-1">+ <label className="text-xs font-medium text-muted mb-0.5 block">Low label</label>+ <LemonInput+ size="small"+ fullWidth+ maxLength={SURVEY_NAME_MAX_LENGTH}+ value={quickForm.ratingLowerLabel}+ onChange={(v) => setFormField('ratingLowerLabel', v)}+ />+ </div>+ <div className="flex-1">+ <label className="text-xs font-medium text-muted mb-0.5 block">High label</label>+ <LemonInput+ size="small"+ fullWidth+ maxLength={SURVEY_NAME_MAX_LENGTH}+ value={quickForm.ratingUpperLabel}+ onChange={(v) => setFormField('ratingUpperLabel', v)}+ />+ </div>+ </div>+ </>+ )}++ {quickForm.questionType === 'single_choice' && (+ <div>+ <label className="text-xs font-medium text-muted mb-0.5 block">Choices</label>+ <div className="space-y-1">+ {quickForm.choices.map((choice, i) => (+ <div key={i} className="flex gap-1 items-center">+ <LemonInput+ size="small"+ fullWidth+ placeholder={`Option ${i + 1}`}+ maxLength={SURVEY_CHOICE_MAX_LENGTH}+ value={choice}+ onChange={(v) => {+ const newChoices = [...quickForm.choices]+ newChoices[i] = v+ setFormField('choices', newChoices)+ }}+ />+ {quickForm.choices.length > 2 && (+ <LemonButton+ size="xsmall"+ icon={<IconTrash />}+ onClick={() => {+ const newChoices = quickForm.choices.filter((_, j) => j !== i)+ setFormField('choices', newChoices)+ }}+ />+ )}+ </div>+ ))}+ {quickForm.choices.length < SURVEY_QUICK_FORM_MAX_CHOICES && (+ <LemonButton+ size="xsmall"+ type="secondary"+ icon={<IconPlus />}+ fullWidth+ onClick={() => setFormField('choices', [...quickForm.choices, ''])}+ >+ Add option+ </LemonButton>+ )}+ </div>+ </div>+ )}+ </div>+ </section>+ )+}++function WhereSection(): JSX.Element {+ const { quickForm } = useValues(surveysToolbarLogic)+ const { setFormField } = useActions(surveysToolbarLogic)++ return (+ <section>+ <h3 className="text-xs font-semibold text-muted-3000 uppercase tracking-wide mb-3">Where</h3>+ <div className="space-y-3">+ <div>+ <LemonRadio+ value={quickForm.targetingMode}+ onChange={(v) => setFormField('targetingMode', v)}+ options={[+ {+ value: 'all',+ label: 'All pages',+ description: 'Survey can appear anywhere on your site',+ },+ {+ value: 'specific',+ label: 'Specific pages',+ description: 'Only show on pages matching a URL pattern',+ },+ ]}+ />+ {quickForm.targetingMode === 'specific' && (+ <div className="mt-2 ml-6 space-y-2">+ <div className="flex gap-1 items-center">+ <LemonInput+ size="small"+ fullWidth+ placeholder="/pricing"+ maxLength={SURVEY_NAME_MAX_LENGTH}+ value={quickForm.urlMatch}+ onChange={(v) => setFormField('urlMatch', v)}+ />+ <LemonSelect+ size="small"+ options={URL_MATCH_TYPE_OPTIONS}+ value={quickForm.urlMatchType}+ onChange={(v) => setFormField('urlMatchType', v)}+ />+ </div>+ <span className="text-xs text-muted block">+ Auto-filled from current page. Pick a match type — exact targets only this URL, contains+ matches any URL containing the value.+ </span>+ </div>+ )}+ </div>+ </div>+ </section>+ )+}++function WhenSection(): JSX.Element {+ const { quickForm } = useValues(surveysToolbarLogic)+ const { setFormField } = useActions(surveysToolbarLogic)++ return (+ <section>+ <h3 className="text-xs font-semibold text-muted-3000 uppercase tracking-wide mb-3">When</h3>+ <div className="space-y-3">+ <div>+ <LemonRadio+ value={quickForm.triggerMode}+ onChange={(v) => setFormField('triggerMode', v)}+ options={[+ {+ value: 'pageview',+ label: 'On page load',+ description: 'Shows when the user visits the page',+ },+ {+ value: 'event',+ label: 'When an event is captured',+ description: 'Trigger the survey after a specific event',+ },+ ]}+ />+ {quickForm.triggerMode === 'event' && (+ <div className="mt-2 ml-6">+ <LemonInput+ size="small"+ fullWidth+ placeholder="e.g. purchase_completed"+ maxLength={SURVEY_NAME_MAX_LENGTH}+ value={quickForm.triggerEventName}+ onChange={(v) => setFormField('triggerEventName', v)}+ />+ <span className="text-xs text-muted mt-0.5 block">+ Enter the event name that triggers this survey+ </span>+ </div>+ )}+ </div>++ <div>+ <p className="text-xs text-muted mb-2">How often can someone see this?</p>+ <LemonSegmentedButton+ value={quickForm.frequency}+ onChange={(v) => setFormField('frequency', v)}+ options={FREQUENCY_OPTIONS.map((opt) => ({+ value: opt.value,+ label: opt.label,+ }))}+ fullWidth+ size="small"+ />+ </div>++ <div>+ <p className="text-xs font-medium text-muted mb-1">Delay before showing</p>+ <div className="flex items-center gap-2">+ <LemonInput+ type="number"+ min={0}+ max={SURVEY_DELAY_MAX_SECONDS}+ size="small"+ value={quickForm.delaySeconds}+ onChange={(val) => setFormField('delaySeconds', clampDelaySeconds(val))}+ className="w-20"+ />+ <span className="text-xs text-muted">seconds after conditions are met</span>+ </div>+ </div>+ </div>+ </section>+ )+}++function statusLabel(status: 'draft' | 'active' | 'complete' | null): string {+ if (status === 'active') {+ return 'Live on your site'+ }+ if (status === 'draft') {+ return 'Draft'+ }+ if (status === 'complete') {+ return 'Ended'+ }+ return ''+}++function statusClass(status: 'draft' | 'active' | 'complete' | null): string {+ if (status === 'active') {+ return 'text-success-3000'+ }+ if (status === 'draft') {+ return 'text-warning-3000'+ }+ return 'text-muted'+}++export function SurveySidebar(): JSX.Element | null {+ const { isCreating, isSubmitting, isLifecyclePending, canProceed, canProceedReason, editingSurvey } =+ useValues(surveysToolbarLogic)+ const { cancelQuickCreate, submitQuickCreate, stopSurvey, resumeSurvey, archiveSurvey } =+ useActions(surveysToolbarLogic)+ const { uiHost } = useValues(toolbarConfigLogic)+ const isEditing = !!editingSurvey+ const status = editingSurvey ? getSurveyStatus(editingSurvey) : null+ const disabledReason = canProceed ? undefined : (canProceedReason ?? 'Add a survey name and question')+ const anyPending = isSubmitting || isLifecyclePending++ // Snapshot host body styles before mutating, restore on cleanup. Naive+ // cleanup to '' would clobber any inline styles the host already had.+ useEffect(() => {+ if (!isCreating) {+ return+ }+ const prevMargin = document.body.style.marginRight+ const prevTransition = document.body.style.transition+ document.body.style.transition = `margin ${SIDEBAR_TRANSITION_MS}ms ease-out`+ document.body.style.marginRight = `${SIDEBAR_WIDTH}px`+ return () => {+ document.body.style.marginRight = prevMargin+ document.body.style.transition = prevTransition+ }+ }, [isCreating])++ if (!isCreating) {+ return null+ }++ const handleEnd = (): void => {+ if (!editingSurvey) {+ return+ }+ if (window.confirm('End this survey now? It will stop showing to new users.')) {+ stopSurvey(editingSurvey)+ }+ }++ const handleResume = (): void => {+ if (!editingSurvey) {+ return+ }+ resumeSurvey(editingSurvey)+ }++ const handleArchive = (): void => {+ if (!editingSurvey) {+ return+ }+ if (+ window.confirm(+ 'Archive this survey? It will be hidden from the toolbar list. You can restore it from the PostHog surveys page.'+ )+ ) {+ archiveSurvey(editingSurvey)+ }+ }++ return (+ <>+ <SurveyLivePreview />+ <div+ className="flex flex-col"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ position: 'fixed',+ top: 0,+ right: 0,+ bottom: 0,+ width: SIDEBAR_WIDTH,+ backgroundColor: 'var(--color-bg-3000)',+ borderLeft: '1px solid var(--border-bold-3000)',+ boxShadow: '-4px 0 24px rgba(0, 0, 0, 0.4)',+ zIndex: SIDEBAR_Z_INDEX,+ pointerEvents: 'auto',+ color: 'var(--text-3000)',+ }}+ >+ {/* Header */}+ <div className="px-4 pt-4 pb-3 border-b border-border-bold-3000 bg-bg-light">+ {/* Title row */}+ <div className="flex items-start justify-between gap-2 mb-3">+ <div className="min-w-0 flex-1">+ <h2 className="m-0 text-sm font-semibold leading-tight truncate">+ {isEditing ? 'Edit survey' : 'New survey'}+ </h2>+ {isEditing && status && (+ <p className={`text-xs font-medium m-0 mt-0.5 ${statusClass(status)}`}>+ {statusLabel(status)}+ </p>+ )}+ </div>+ <div className="flex items-center gap-1 shrink-0">+ {isEditing && editingSurvey && (+ <LemonMenu+ placement="bottom-end"+ items={[+ {+ label: 'Archive survey',+ icon: <IconArchive />,+ status: 'danger',+ onClick: handleArchive,+ disabledReason: anyPending ? 'Action in progress' : undefined,+ },+ ]}+ >+ <LemonButton+ size="xsmall"+ type="tertiary"+ icon={<IconEllipsis />}+ tooltip="More actions"+ />+ </LemonMenu>+ )}+ <button+ type="button"+ onClick={cancelQuickCreate}+ aria-label="Close"+ disabled={isSubmitting}+ className="p-1 rounded border-none bg-transparent cursor-pointer text-muted-3000 hover:text-text-3000 flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed"+ >+ <IconX className="w-4 h-4" />+ </button>+ </div>+ </div>++ {/* Primary action row — pairs save with the most relevant lifecycle action */}+ {isEditing && editingSurvey ? (+ <div className="flex gap-2">+ {status === 'draft' && (+ <>+ <LemonButton+ type="tertiary"+ center+ className="flex-1"+ loading={isSubmitting}+ disabledReason={disabledReason}+ onClick={() => submitQuickCreate(false)}+ >+ Save changes+ </LemonButton>+ <LemonButton+ type="primary"+ center+ className="flex-1"+ icon={<IconRocket />}+ loading={isSubmitting}+ disabledReason={disabledReason}+ onClick={() => submitQuickCreate(true)}+ >+ Launch+ </LemonButton>+ </>+ )}+ {status === 'active' && (+ <>+ <LemonButton+ type="tertiary"+ center+ className="flex-1"+ loading={isLifecyclePending}+ disabledReason={anyPending ? 'Action in progress' : undefined}+ onClick={handleEnd}+ >+ End survey+ </LemonButton>+ <LemonButton+ type="primary"+ center+ className="flex-1"+ loading={isSubmitting}+ disabledReason={disabledReason}+ onClick={() => submitQuickCreate(false)}+ >+ Save changes+ </LemonButton>+ </>+ )}+ {status === 'complete' && (+ <>+ <LemonButton+ type="tertiary"+ center+ className="flex-1"+ loading={isLifecyclePending}+ disabledReason={anyPending ? 'Action in progress' : undefined}+ onClick={handleResume}+ >+ Resume+ </LemonButton>+ <LemonButton+ type="primary"+ center+ className="flex-1"+ loading={isSubmitting}+ disabledReason={disabledReason}+ onClick={() => submitQuickCreate(false)}+ >+ Save changes+ </LemonButton>+ </>+ )}+ </div>+ ) : (+ <div className="flex gap-2">+ <LemonButton+ type="tertiary"+ center+ className="flex-1"+ loading={isSubmitting}+ disabledReason={disabledReason}+ onClick={() => submitQuickCreate(false)}+ >+ Save draft+ </LemonButton>+ <LemonButton+ type="primary"+ center+ className="flex-1"+ icon={<IconRocket />}+ loading={isSubmitting}+ disabledReason={disabledReason}+ onClick={() => submitQuickCreate(true)}+ >+ Launch+ </LemonButton>+ </div>+ )}+ </div>++ {/* Scrollable form body */}+ <div className="flex-1 overflow-y-auto p-4 space-y-5">+ {/* Compact info strip */}+ <p className="text-xs text-muted m-0 leading-snug">+ Quick editor for single-question surveys. Need branching or multiple questions?{' '}+ <Link to={joinWithUiHost(uiHost, urls.surveys())} target="_blank" subtle>+ Open in PostHog <IconExternal className="inline w-3 h-3" />+ </Link>+ </p>+ <QuestionSection />+ <div className="border-t border-border-bold-3000" />+ <WhereSection />+ <div className="border-t border-border-bold-3000" />+ <WhenSection />+ </div>+ </div>+ </>+ )+}diff --git a/frontend/src/toolbar/surveys/SurveysToolbarMenu.tsx b/frontend/src/toolbar/surveys/SurveysToolbarMenu.tsxindex 753108a25d0f..0607d8a80425 100644--- a/frontend/src/toolbar/surveys/SurveysToolbarMenu.tsx+++ b/frontend/src/toolbar/surveys/SurveysToolbarMenu.tsx@@ -1,111 +1,5 @@-import { useActions, useValues } from 'kea'--import { LemonBadge, LemonSkeleton } from '@posthog/lemon-ui'--import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'-import { IconOpenInNew } from 'lib/lemon-ui/icons'-import { LemonInput } from 'lib/lemon-ui/LemonInput'-import { Link } from 'lib/lemon-ui/Link'-import { urls } from 'scenes/urls'--import { ToolbarMenu } from '~/toolbar/bar/ToolbarMenu'-import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'-import { joinWithUiHost } from '~/toolbar/utils'-import { Survey, SurveyType } from '~/types'--import { getSurveyStatus, surveysToolbarLogic } from './surveysToolbarLogic'--const SURVEY_TYPE_LABELS: Record<SurveyType, string> = {- [SurveyType.Popover]: 'Popover',- [SurveyType.Widget]: 'Widget',- [SurveyType.FullScreen]: 'Full screen',- [SurveyType.API]: 'API',- [SurveyType.ExternalSurvey]: 'External',-}--const STATUS_COLORS: Record<string, 'primary' | 'muted' | 'danger'> = {- active: 'primary',- draft: 'muted',- complete: 'muted',-}--function SurveyRow({ survey }: { survey: Survey }): JSX.Element {- const { uiHost } = useValues(toolbarConfigLogic)- const status = getSurveyStatus(survey)- const typeLabel = SURVEY_TYPE_LABELS[survey.type] ?? survey.type-- return (- <div className="flex items-center gap-2 py-1.5 px-1 -mx-1 rounded hover:bg-fill-primary-hover">- <div className="flex-1 min-w-0">- <div className="flex items-center gap-1.5">- <Link- className="font-medium truncate"- to={joinWithUiHost(uiHost, urls.survey(survey.id))}- subtle- target="_blank"- >- {survey.name}- <IconOpenInNew className="ml-0.5" />- </Link>- </div>- <div className="flex items-center gap-1.5 mt-0.5">- <span className="text-xs text-muted">{typeLabel}</span>- <span className="text-xs text-muted">·</span>- <LemonBadge size="small" status={STATUS_COLORS[status] ?? 'muted'} content={status} />- {survey.questions.length > 0 && (- <>- <span className="text-xs text-muted">·</span>- <span className="text-xs text-muted">- {survey.questions.length} {survey.questions.length === 1 ? 'question' : 'questions'}- </span>- </>- )}- </div>- </div>- </div>- )-}+import { SurveyListView } from './SurveyListView'export function SurveysToolbarMenu(): JSX.Element {- const { searchTerm, allSurveys, allSurveysLoading } = useValues(surveysToolbarLogic)- const { setSearchTerm, loadSurveys } = useActions(surveysToolbarLogic)-- useOnMountEffect(() => {- loadSurveys()- })-- return (- <ToolbarMenu>- <ToolbarMenu.Header>- <LemonInput- autoFocus- placeholder="Search surveys"- fullWidth- type="search"- value={searchTerm}- onChange={(s) => setSearchTerm(s)}- />- </ToolbarMenu.Header>- <ToolbarMenu.Body>- <div className="mt-1">- {allSurveysLoading ? (- <div className="space-y-3 py-1">- {Array.from({ length: 3 }).map((_, i) => (- <div key={i} className="space-y-1.5 py-1">- <LemonSkeleton className="h-4 w-3/4" />- <LemonSkeleton className="h-3 w-1/2" />- </div>- ))}- </div>- ) : allSurveys.length > 0 ? (- allSurveys.map((survey: Survey) => <SurveyRow key={survey.id} survey={survey} />)- ) : (- <div className="text-muted text-sm text-center py-4">- {searchTerm ? 'No matching surveys found.' : 'No surveys found in this project.'}- </div>- )}- </div>- </ToolbarMenu.Body>- </ToolbarMenu>- )+ return <SurveyListView />}diff --git a/frontend/src/toolbar/surveys/constants.tsx b/frontend/src/toolbar/surveys/constants.tsxnew file mode 100644index 000000000000..ae98c886243e--- /dev/null+++ b/frontend/src/toolbar/surveys/constants.tsx@@ -0,0 +1,17 @@+import { SurveyType } from '~/types'++export const SURVEY_TYPE_LABELS: Record<SurveyType, string> = {+ [SurveyType.Popover]: 'Popover',+ [SurveyType.Widget]: 'Widget',+ [SurveyType.FullScreen]: 'Full screen',+ [SurveyType.API]: 'API',+ [SurveyType.ExternalSurvey]: 'External',+}++export const STATUS_COLORS: Record<string, 'primary' | 'muted' | 'danger'> = {+ active: 'primary',+ draft: 'muted',+ complete: 'muted',+}++export const SIDEBAR_WIDTH = 380diff --git a/frontend/src/toolbar/surveys/surveysToolbarLogic.ts b/frontend/src/toolbar/surveys/surveysToolbarLogic.tsindex 46f02968d546..af5d35d6dece 100644--- a/frontend/src/toolbar/surveys/surveysToolbarLogic.ts+++ b/frontend/src/toolbar/surveys/surveysToolbarLogic.ts@@ -1,13 +1,87 @@-import { actions, kea, listeners, path, reducers } from 'kea'+import { actions, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'-import { toolbarFetch } from '~/toolbar/toolbarConfigLogic'-import { Survey } from '~/types'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { urls } from 'scenes/urls'++import { toolbarLogic } from '~/toolbar/bar/toolbarLogic'+import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'+import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'+import { joinWithUiHost } from '~/toolbar/utils'+import {+ Survey,+ SurveyAppearance,+ SurveyMatchType,+ SurveyPosition,+ SurveyQuestionType,+ SurveySchedule,+ SurveyType,+} from '~/types'import type { surveysToolbarLogicType } from './surveysToolbarLogicType'export type SurveyStatus = 'draft' | 'active' | 'complete'+export type QuickSurveyQuestionType = 'open' | 'rating' | 'single_choice'++export type TargetingMode = 'all' | 'specific'+export type FrequencyOption = 'once' | 'yearly' | 'quarterly' | 'monthly'+export type TriggerMode = 'pageview' | 'event'++const SURVEYS_PAGE_SIZE = 20+export const SURVEY_PREVIEW_Z_INDEX = 2147482647+export const SURVEY_DELAY_MAX_SECONDS = 3600+export const SURVEY_NAME_MAX_LENGTH = 200+export const SURVEY_QUESTION_MAX_LENGTH = 1000+export const SURVEY_CHOICE_MAX_LENGTH = 200+export const SURVEY_QUICK_FORM_MAX_CHOICES = 6++export const FREQUENCY_OPTIONS: { value: FrequencyOption; days: number | undefined; label: string }[] = [+ { value: 'once', days: undefined, label: 'Once' },+ { value: 'yearly', days: 365, label: 'Yearly' },+ { value: 'quarterly', days: 90, label: 'Quarterly' },+ { value: 'monthly', days: 30, label: 'Monthly' },+]++export interface QuickSurveyForm {+ name: string+ questionType: QuickSurveyQuestionType+ questionText: string+ ratingScale: 5 | 10+ ratingLowerLabel: string+ ratingUpperLabel: string+ choices: string[]+ // Where+ targetingMode: TargetingMode+ urlMatch: string+ urlMatchType: SurveyMatchType+ // When - frequency+ frequency: FrequencyOption+ // When - trigger+ triggerMode: TriggerMode+ triggerEventName: string+ delaySeconds: number+}++export const EMPTY_FORM: QuickSurveyForm = {+ name: '',+ questionType: 'open',+ questionText: '',+ ratingScale: 5,+ ratingLowerLabel: 'Not likely',+ ratingUpperLabel: 'Very likely',+ choices: ['', ''],+ targetingMode: 'specific',+ urlMatch: '',+ // Default to exact for the auto-filled current page — users targeting "this+ // page" usually mean exactly that, not contains.+ urlMatchType: SurveyMatchType.Exact,+ frequency: 'once',+ triggerMode: 'pageview',+ triggerEventName: '',+ delaySeconds: 0,+}+export function getSurveyStatus(survey: Survey): SurveyStatus {if (!survey.start_date) {return 'draft'@@ -18,6 +92,285 @@ export function getSurveyStatus(survey: Survey): SurveyStatus {return 'active'}+/**+ * Whether the quick-create form can faithfully round-trip this survey. We+ * deliberately reject anything we can't represent exactly so an "Edit in+ * toolbar" save never silently drops or downgrades data.+ */+export function isQuickEditable(survey: Survey): boolean {+ if (survey.type !== SurveyType.Popover) {+ return false+ }+ if (survey.questions.length !== 1) {+ return false+ }+ const q = survey.questions[0]+ const isSupportedType =+ q.type === SurveyQuestionType.Open ||+ q.type === SurveyQuestionType.Rating ||+ q.type === SurveyQuestionType.SingleChoice+ if (!isSupportedType) {+ return false+ }+ // Single-choice surveys with non-empty answer set within our cap. Empty+ // strings here would get silently filtered on save.+ if (q.type === SurveyQuestionType.SingleChoice) {+ const choices = q.choices ?? []+ if (choices.length === 0 || choices.length > SURVEY_QUICK_FORM_MAX_CHOICES) {+ return false+ }+ if (choices.some((c) => !c || !c.trim())) {+ return false+ }+ }+ // Rating: only the scale values our form exposes.+ if (q.type === SurveyQuestionType.Rating) {+ const scale = q.scale+ if (scale !== 5 && scale !== 10) {+ return false+ }+ }+ // Frequency must map to one of the form's options — anything else (e.g.+ // a custom 60-day cadence) would silently downgrade to "Once" on save.+ const wait = survey.conditions?.seenSurveyWaitPeriodInDays+ if (wait !== undefined && wait !== null && !FREQUENCY_OPTIONS.some((o) => o.days === wait)) {+ return false+ }+ return true+}++function surveyToForm(survey: Survey): QuickSurveyForm {+ const q = survey.questions[0]+ let questionType: QuickSurveyQuestionType = 'open'+ let ratingScale: 5 | 10 = 5+ let ratingLowerLabel = EMPTY_FORM.ratingLowerLabel+ let ratingUpperLabel = EMPTY_FORM.ratingUpperLabel+ let choices: string[] = ['', '']++ if (q.type === SurveyQuestionType.Rating) {+ questionType = 'rating'+ ratingScale = q.scale === 10 ? 10 : 5+ ratingLowerLabel = q.lowerBoundLabel ?? ratingLowerLabel+ ratingUpperLabel = q.upperBoundLabel ?? ratingUpperLabel+ } else if (q.type === SurveyQuestionType.SingleChoice) {+ questionType = 'single_choice'+ choices = q.choices && q.choices.length >= 2 ? [...q.choices] : ['', '']+ }++ const conditions = survey.conditions ?? null+ const targetingMode: TargetingMode = conditions?.url ? 'specific' : 'all'+ const urlMatch = conditions?.url ?? ''+ const urlMatchType = conditions?.urlMatchType ?? EMPTY_FORM.urlMatchType++ let frequency: FrequencyOption = 'once'+ if (conditions?.seenSurveyWaitPeriodInDays) {+ frequency = FREQUENCY_OPTIONS.find((o) => o.days === conditions.seenSurveyWaitPeriodInDays)?.value ?? 'once'+ }++ let triggerMode: TriggerMode = 'pageview'+ let triggerEventName = ''+ const eventValues = conditions?.events?.values+ if (eventValues && eventValues.length > 0) {+ triggerMode = 'event'+ triggerEventName = eventValues[0]?.name ?? ''+ }++ const rawDelay = (survey.appearance as SurveyAppearance | null)?.surveyPopupDelaySeconds+ const delaySeconds = clampDelaySeconds(rawDelay)++ return {+ name: survey.name,+ questionType,+ questionText: q.question,+ ratingScale,+ ratingLowerLabel,+ ratingUpperLabel,+ choices,+ targetingMode,+ urlMatch,+ urlMatchType,+ frequency,+ triggerMode,+ triggerEventName,+ delaySeconds,+ }+}++export function clampDelaySeconds(value: unknown): number {+ const n = typeof value === 'number' ? value : Number(value)+ if (!Number.isFinite(n) || n <= 0) {+ return 0+ }+ return Math.min(SURVEY_DELAY_MAX_SECONDS, Math.floor(n))+}++const DEFAULT_APPEARANCE: SurveyAppearance = {+ fontFamily: 'inherit',+ backgroundColor: '#eeeded',+ submitButtonColor: 'black',+ submitButtonTextColor: 'white',+ ratingButtonColor: 'white',+ ratingButtonActiveColor: 'black',+ borderColor: '#c9c6c6',+ placeholder: 'Start typing...',+ displayThankYouMessage: true,+ thankYouMessageHeader: 'Thank you for your feedback!',+ position: SurveyPosition.Right,+ zIndex: String(SURVEY_PREVIEW_Z_INDEX),+ maxWidth: '300px',+ boxPadding: '20px 24px',+ boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',+ borderRadius: '10px',+}++interface BuildPayloadOptions {+ /** When set, merge form-controlled fields onto the existing survey's+ * appearance/conditions instead of overwriting with defaults. */+ existing?: Survey | null+}++function buildSurveyPayload(form: QuickSurveyForm, opts: BuildPayloadOptions = {}): Record<string, unknown> {+ const questions: Record<string, unknown>[] = []++ if (form.questionType === 'open') {+ questions.push({+ type: SurveyQuestionType.Open,+ question: form.questionText,+ buttonText: 'Submit',+ })+ } else if (form.questionType === 'rating') {+ questions.push({+ type: SurveyQuestionType.Rating,+ question: form.questionText,+ display: 'number',+ scale: form.ratingScale,+ lowerBoundLabel: form.ratingLowerLabel,+ upperBoundLabel: form.ratingUpperLabel,+ buttonText: 'Submit',+ })+ } else if (form.questionType === 'single_choice') {+ questions.push({+ type: SurveyQuestionType.SingleChoice,+ question: form.questionText,+ choices: form.choices.filter((c) => c.trim() !== ''),+ buttonText: 'Submit',+ })+ }++ // Conditions: when editing, preserve fields the form doesn't model+ // (selector, deviceTypes, actions, cancelEvents, linkedFlagVariant, etc.).+ const existingConditions = opts.existing?.conditions ?? null+ const baseConditions: Record<string, unknown> = existingConditions ? { ...existingConditions } : {}++ // URL targeting — completely controlled by the form.+ if (form.targetingMode === 'specific' && form.urlMatch) {+ baseConditions.url = form.urlMatch+ baseConditions.urlMatchType = form.urlMatchType+ } else {+ delete baseConditions.url+ delete baseConditions.urlMatchType+ }++ // Frequency — completely controlled by the form.+ const frequencyOption = FREQUENCY_OPTIONS.find((o) => o.value === form.frequency)+ if (frequencyOption?.days) {+ baseConditions.seenSurveyWaitPeriodInDays = frequencyOption.days+ } else {+ delete baseConditions.seenSurveyWaitPeriodInDays+ }++ // Event trigger — controlled by the form. Preserve repeatedActivation if+ // the existing survey had one.+ if (form.triggerMode === 'event' && form.triggerEventName.trim()) {+ const previousRepeated =+ (existingConditions?.events as { repeatedActivation?: boolean } | null | undefined)?.repeatedActivation ??+ false+ baseConditions.events = {+ values: [{ name: form.triggerEventName.trim() }],+ repeatedActivation: previousRepeated,+ }+ } else {+ delete baseConditions.events+ }++ const conditions = Object.keys(baseConditions).length > 0 ? baseConditions : null++ // Appearance: when editing, only the fields the form controls (currently+ // surveyPopupDelaySeconds) should change. When creating, seed from defaults.+ const baseAppearance: Record<string, unknown> = opts.existing?.appearance+ ? { ...(opts.existing.appearance as Record<string, unknown>) }+ : { ...(DEFAULT_APPEARANCE as Record<string, unknown>) }+ if (form.delaySeconds > 0) {+ baseAppearance.surveyPopupDelaySeconds = form.delaySeconds+ } else {+ delete baseAppearance.surveyPopupDelaySeconds+ }++ // Schedule+ const schedule = form.frequency === 'once' ? SurveySchedule.Once : SurveySchedule.Always++ const payload: Record<string, unknown> = {+ name: form.name,+ questions,+ schedule,+ appearance: baseAppearance,+ conditions,+ }+ if (!opts.existing) {+ // New survey — set type and start as draft.+ payload.type = SurveyType.Popover+ payload.start_date = null+ }+ return payload+}++async function patchAndRefreshSurvey(+ surveyId: string,+ payload: Record<string, unknown>,+ successMessage: string+): Promise<boolean> {+ try {+ const response = await toolbarFetch(`/api/projects/@current/surveys/${surveyId}/`, 'PATCH', payload)+ if (!response.ok) {+ const error = await response.json().catch(() => ({}))+ lemonToast.error(formatApiError(error, response.status, 'Failed to update survey'))+ return false+ }+ lemonToast.success(successMessage)+ return true+ } catch (e) {+ // eslint-disable-next-line no-console+ console.warn('[Toolbar] survey lifecycle update failed', e)+ lemonToast.error('Failed to update survey')+ return false+ }+}++function formatApiError(error: unknown, status: number, fallback: string): string {+ if (status === 401 || status === 403) {+ return 'Your toolbar session lacks permission. Please re-authenticate the toolbar from PostHog.'+ }+ if (error && typeof error === 'object') {+ const errObj = error as Record<string, unknown>+ if (typeof errObj.detail === 'string' && errObj.detail) {+ return errObj.detail+ }+ // Surface DRF field-level errors: { name: ["..."], questions: [...] }.+ const fieldMessages: string[] = []+ for (const [key, value] of Object.entries(errObj)) {+ if (Array.isArray(value) && value.length > 0 && typeof value[0] === 'string') {+ fieldMessages.push(`${key}: ${value[0]}`)+ } else if (typeof value === 'string') {+ fieldMessages.push(`${key}: ${value}`)+ }+ }+ if (fieldMessages.length > 0) {+ return fieldMessages.join('; ')+ }+ }+ return fallback+}+export const surveysToolbarLogic = kea<surveysToolbarLogicType>([path(['toolbar', 'surveys', 'surveysToolbarLogic']),@@ -25,25 +378,78 @@ export const surveysToolbarLogic = kea<surveysToolbarLogicType>([setSearchTerm: (searchTerm: string) => ({ searchTerm }),showButtonSurveys: true,hideButtonSurveys: true,+ // Quick-create / quick-edit flow (shares the same sidebar form)+ startQuickCreate: true,+ startQuickEdit: (survey: Survey) => ({ survey }),+ cancelQuickCreate: true,+ setFormField: (field: keyof QuickSurveyForm, value: unknown) => ({ field, value }),+ submitQuickCreate: (launch: boolean = false) => ({ launch }),+ submitQuickCreateSuccess: true,+ submitQuickCreateFailure: true,+ // Lifecycle (launch / stop / resume / archive)+ launchSurvey: (survey: Survey) => ({ survey }),+ stopSurvey: (survey: Survey) => ({ survey }),+ resumeSurvey: (survey: Survey) => ({ survey }),+ archiveSurvey: (survey: Survey) => ({ survey }),+ setLifecyclePending: (pending: boolean) => ({ pending }),+ // Pagination — loadMoreSurveys is auto-declared by the loader below+ setHasMoreSurveys: (hasMore: boolean) => ({ hasMore }),}),- loaders(({ values }) => ({+ loaders(({ values, actions }) => ({allSurveys: [[] as Survey[],{loadSurveys: async () => {+ const search = values.searchTermconst params = new URLSearchParams()params.set('archived', 'false')- if (values.searchTerm) {- params.set('search', values.searchTerm)+ params.set('limit', String(SURVEYS_PAGE_SIZE))+ params.set('offset', '0')+ if (search) {+ params.set('search', search)}const url = `/api/projects/@current/surveys/?${params}`const response = await toolbarFetch(url)+ // If the search term changed while we were awaiting,+ // abandon this result to avoid clobbering newer state.+ if (search !== values.searchTerm) {+ return values.allSurveys+ }if (!response.ok) {+ actions.setHasMoreSurveys(false)return []}- const data = await response.json()- return data.results ?? data+ const data = await response.json().catch(() => ({}))+ actions.setHasMoreSurveys(!!data.next)+ return data.results ?? data ?? []+ },+ loadMoreSurveys: async () => {+ if (!values.hasMoreSurveys || values.allSurveysLoading) {+ return values.allSurveys+ }+ const search = values.searchTerm+ const previousIds = new Set(values.allSurveys.map((s) => s.id))+ const params = new URLSearchParams()+ params.set('archived', 'false')+ params.set('limit', String(SURVEYS_PAGE_SIZE))+ params.set('offset', String(values.allSurveys.length))+ if (search) {+ params.set('search', search)+ }+ const url = `/api/projects/@current/surveys/?${params}`+ const response = await toolbarFetch(url)+ // Search changed while we were paging — drop the result.+ if (search !== values.searchTerm) {+ return values.allSurveys+ }+ if (!response.ok) {+ return values.allSurveys+ }+ const data = await response.json().catch(() => ({}))+ actions.setHasMoreSurveys(!!data.next)+ const newRows: Survey[] = (data.results ?? data ?? []).filter((s: Survey) => !previousIds.has(s.id))+ return [...values.allSurveys, ...newRows]},},],@@ -56,12 +462,281 @@ export const surveysToolbarLogic = kea<surveysToolbarLogicType>([setSearchTerm: (_, { searchTerm }) => searchTerm,},],+ isCreating: [+ false,+ {+ startQuickCreate: () => true,+ startQuickEdit: () => true,+ cancelQuickCreate: () => false,+ submitQuickCreateSuccess: () => false,+ },+ ],+ editingSurveyId: [+ null as string | null,+ {+ startQuickCreate: () => null,+ startQuickEdit: (_, { survey }) => survey.id,+ cancelQuickCreate: () => null,+ submitQuickCreateSuccess: () => null,+ },+ ],+ // Snapshot the survey at edit-start so we don't depend on it being+ // present in `allSurveys` (the list can reload mid-edit).+ editingSurvey: [+ null as Survey | null,+ {+ startQuickCreate: () => null,+ startQuickEdit: (_, { survey }) => survey,+ cancelQuickCreate: () => null,+ submitQuickCreateSuccess: () => null,+ },+ ],+ quickForm: [+ { ...EMPTY_FORM } as QuickSurveyForm,+ {+ startQuickCreate: () => ({+ ...EMPTY_FORM,+ urlMatch: window.location.pathname,+ urlMatchType: SurveyMatchType.Exact,+ }),+ startQuickEdit: (_, { survey }) => surveyToForm(survey),+ cancelQuickCreate: () => ({ ...EMPTY_FORM }),+ setFormField: (state, { field, value }) => {+ if (field === 'delaySeconds') {+ return { ...state, delaySeconds: clampDelaySeconds(value) }+ }+ return { ...state, [field]: value as never }+ },+ submitQuickCreateSuccess: () => ({ ...EMPTY_FORM }),+ },+ ],+ isSubmitting: [+ false,+ {+ submitQuickCreate: () => true,+ submitQuickCreateSuccess: () => false,+ submitQuickCreateFailure: () => false,+ },+ ],+ isLifecyclePending: [+ false,+ {+ setLifecyclePending: (_, { pending }) => pending,+ },+ ],+ hasMoreSurveys: [+ false,+ {+ setHasMoreSurveys: (_, { hasMore }) => hasMore,+ loadSurveys: () => false,+ },+ ],+ }),++ selectors({+ previewSurvey: [+ (s) => [s.quickForm, s.isCreating, s.editingSurvey],+ (form, isCreating, editingSurvey): Survey | null => {+ if (!isCreating) {+ return null+ }+ const previewForm: QuickSurveyForm = {+ ...form,+ questionText: form.questionText || 'Your question will appear here',+ name: form.name || 'Untitled survey',+ }+ const payload = buildSurveyPayload(previewForm, { existing: editingSurvey })+ // Build the minimal shape that the surveys preview renderer reads.+ // Cast through `unknown` so we don't have to pretend to satisfy+ // every Survey field (created_by, archived, linked_flag_id, etc.).+ // No wall-clock fields here — the selector must be referentially+ // stable when inputs are unchanged so downstream effects can dedupe.+ return {+ id: 'preview',+ name: previewForm.name,+ description: '',+ type: SurveyType.Popover,+ questions: payload.questions as Survey['questions'],+ appearance: (payload.appearance as SurveyAppearance) ?? null,+ conditions: (payload.conditions as Survey['conditions']) ?? null,+ start_date: null,+ end_date: null,+ created_at: '1970-01-01T00:00:00.000Z',+ linked_flag: null,+ targeting_flag: null,+ responses_limit: null,+ } as unknown as Survey+ },+ ],+ canProceed: [+ (s) => [s.quickForm],+ (form): boolean => {+ return (+ !!form.name.trim() &&+ !!form.questionText.trim() &&+ (form.questionType !== 'single_choice' ||+ form.choices.filter((c: string) => c.trim() !== '').length >= 2)+ )+ },+ ],+ // Surface a concrete reason the submit button is disabled — generic+ // "Fill in the name and question" misleads users who are stuck on+ // "needs at least two single-choice options".+ canProceedReason: [+ (s) => [s.quickForm],+ (form): string | null => {+ if (!form.name.trim()) {+ return 'Add a survey name'+ }+ if (!form.questionText.trim()) {+ return 'Add a question'+ }+ if (form.questionType === 'single_choice') {+ const filled = form.choices.filter((c) => c.trim() !== '').length+ if (filled < 2) {+ return 'Add at least two answer options'+ }+ }+ return null+ },+ ],}),- listeners(({ actions }) => ({+ listeners(({ actions, values }) => ({+ startQuickCreate: () => {+ toolbarLogic.actions.setVisibleMenu('none')+ },+ startQuickEdit: () => {+ toolbarLogic.actions.setVisibleMenu('none')+ },setSearchTerm: async (_, breakpoint) => {await breakpoint(300)actions.loadSurveys()},+ launchSurvey: async ({ survey }) => {+ if (values.isLifecyclePending) {+ return+ }+ actions.setLifecyclePending(true)+ const ok = await patchAndRefreshSurvey(+ survey.id,+ { start_date: new Date().toISOString() },+ 'Survey launched'+ )+ actions.setLifecyclePending(false)+ actions.loadSurveys()+ if (ok) {+ actions.cancelQuickCreate()+ }+ },+ stopSurvey: async ({ survey }) => {+ if (values.isLifecyclePending) {+ return+ }+ actions.setLifecyclePending(true)+ const ok = await patchAndRefreshSurvey(survey.id, { end_date: new Date().toISOString() }, 'Survey ended')+ actions.setLifecyclePending(false)+ actions.loadSurveys()+ if (ok) {+ actions.cancelQuickCreate()+ }+ },+ resumeSurvey: async ({ survey }) => {+ if (values.isLifecyclePending) {+ return+ }+ actions.setLifecyclePending(true)+ const ok = await patchAndRefreshSurvey(survey.id, { end_date: null }, 'Survey resumed')+ actions.setLifecyclePending(false)+ actions.loadSurveys()+ if (ok) {+ actions.cancelQuickCreate()+ }+ },+ archiveSurvey: async ({ survey }) => {+ if (values.isLifecyclePending) {+ return+ }+ actions.setLifecyclePending(true)+ const ok = await patchAndRefreshSurvey(survey.id, { archived: true }, 'Survey archived')+ actions.setLifecyclePending(false)+ actions.loadSurveys()+ if (ok) {+ actions.cancelQuickCreate()+ }+ },+ submitQuickCreate: async ({ launch }) => {+ // Re-entrancy guard: button shows loading, but a fast keyboard+ // accelerator can fire twice before the reducer commits.+ if (values.isSubmitting) {+ return+ }+ const editingId = values.editingSurveyId+ const editingSurvey = values.editingSurvey+ const payload = buildSurveyPayload(values.quickForm, { existing: editingId ? editingSurvey : null })+ // When editing, "Launch" forces start_date to now; "Save" preserves+ // the survey's current launch state (don't sneak-launch or sneak-end).+ if (launch) {+ payload.start_date = new Date().toISOString()+ } else if (editingId) {+ delete payload.start_date+ }+ try {+ const response = await toolbarFetch(+ editingId ? `/api/projects/@current/surveys/${editingId}/` : '/api/projects/@current/surveys/',+ editingId ? 'PATCH' : 'POST',+ payload+ )+ // If the user cancelled while we were awaiting, drop the result+ // silently — they explicitly threw the work away.+ if (!values.isCreating) {+ return+ }+ if (!response.ok) {+ const error = await response.json().catch(() => ({}))+ lemonToast.error(+ formatApiError(+ error,+ response.status,+ editingId ? 'Failed to save survey' : 'Failed to create survey'+ )+ )+ actions.submitQuickCreateFailure()+ return+ }+ const saved = await response.json().catch(() => ({}))+ toolbarPosthogJS.capture(editingId ? 'toolbar survey edited' : 'toolbar survey created', {+ question_type: values.quickForm.questionType,+ has_url_targeting: values.quickForm.targetingMode === 'specific',+ frequency: values.quickForm.frequency,+ trigger_mode: values.quickForm.triggerMode,+ launched: launch,+ })+ const { uiHost } = toolbarConfigLogic.values+ const surveyUrl = saved.id ? joinWithUiHost(uiHost, urls.survey(saved.id)) : null+ const message = editingId+ ? launch+ ? 'Survey saved and launched'+ : 'Survey saved'+ : launch+ ? 'Survey launched'+ : 'Draft survey created'+ lemonToast.success(message, {+ button: surveyUrl+ ? {+ label: 'Open in PostHog',+ action: () => window.open(surveyUrl, '_blank'),+ }+ : undefined,+ })+ actions.submitQuickCreateSuccess()+ actions.loadSurveys()+ } catch (e) {+ // eslint-disable-next-line no-console+ console.warn('[Toolbar] survey submit failed', e)+ lemonToast.error(editingId ? 'Failed to save survey' : 'Failed to create survey')+ actions.submitQuickCreateFailure()+ }+ },})),])diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex da41f8e5d8ba..3fe51071d31d 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -727,6 +727,7 @@ TOOLBAR_OAUTH_SCOPES = ["element:read","uploaded_media:write","survey:read",+ "survey:write",]ELEMENT_STATS_DEFAULT_LIMIT = get_from_env("ELEMENT_STATS_DEFAULT_LIMIT", 50_000, type_cast=int)