: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
chore(toolbar): remove the quick survey creator (#115619)
Rafael Audiberteff814e35f29
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 95a9ac85945f..977c35df9a07 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -564,7 +564,6 @@ export const FEATURE_FLAGS = {SURVEYS_ERROR_TRACKING_CROSS_SELL: 'surveys-in-error-tracking', // owner: @adboio #team-surveysSURVEYS_FORM_BUILDER: 'surveys-form-builder', // owner: @adboio #team-surveysSURVEYS_INSIGHT_BUTTON_EXPERIMENT: 'ask-users-why-ai-vs-quickcreate', // owner: @adboio #team-surveys multivariate=true- SURVEYS_TOOLBAR: 'surveys-toolbar', // owner: @fcgomesSURVEYS_WEB_ANALYTICS_CROSS_SELL: 'surveys-in-web-analytics', // owner: @adboio #team-surveysTASK_SUMMARIES: 'task-summaries', // owner: #team-ai-observabilityTASK_TOOL: 'phai-task-tool', // owner: @kappa90 #team-posthog-aidiff --git a/frontend/src/toolbar/bar/Toolbar.scss b/frontend/src/toolbar/bar/Toolbar.scssindex dca822d5f0e2..61b01ba4d55a 100644--- a/frontend/src/toolbar/bar/Toolbar.scss+++ b/frontend/src/toolbar/bar/Toolbar.scss@@ -153,10 +153,6 @@--toolbar-width-expanded: 460px;}- &--extra-buttons-4 {- --toolbar-width-expanded: 502px;- }-&--minimized {width: var(--toolbar-width-minimized); // Account for borderdiff --git a/frontend/src/toolbar/bar/Toolbar.tsx b/frontend/src/toolbar/bar/Toolbar.tsxindex 864ea9401a72..b47ac03a737e 100644--- a/frontend/src/toolbar/bar/Toolbar.tsx+++ b/frontend/src/toolbar/bar/Toolbar.tsx@@ -18,7 +18,6 @@ import {IconLeave,IconLive,IconLock,- IconMessage,IconNight,IconPieChart,IconQuestion,@@ -48,7 +47,6 @@ import { fieldNotesLogic } from '~/toolbar/field-notes/fieldNotesLogic'import { productToursLogic } from '~/toolbar/product-tours/productToursLogic'import { screenshotUploadLogic } from '~/toolbar/screenshot-upload/screenshotUploadLogic'import { ScreenshotUploadModal } from '~/toolbar/screenshot-upload/ScreenshotUploadModal'-import { surveysToolbarLogic } from '~/toolbar/surveys/surveysToolbarLogic'import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'import {ToolbarFeatureGateStatus,@@ -104,14 +102,6 @@ const ProductToursToolbarMenu = lazy(() =>const HeatmapToolbarMenu = lazy(() =>retryImport(() => import('~/toolbar/stats/HeatmapToolbarMenu')).then((m) => ({ default: m.HeatmapToolbarMenu })))-const SurveySidebar = lazy(() =>- retryImport(() => import('~/toolbar/surveys/SurveySidebar')).then((m) => ({ default: m.SurveySidebar }))-)-const SurveysToolbarMenu = lazy(() =>- retryImport(() => import('~/toolbar/surveys/SurveysToolbarMenu')).then((m) => ({- default: m.SurveysToolbarMenu,- }))-)const WebVitalsToolbarMenu = lazy(() =>retryImport(() => import('~/toolbar/web-vitals/WebVitalsToolbarMenu')).then((m) => ({default: m.WebVitalsToolbarMenu,@@ -401,9 +391,6 @@ export function ToolbarInfoMenu(): JSX.Element | null {const productToursFlag = useToolbarFeatureFlag('product-tours-2025')const showProductTours = inStorybook() || inStorybookTestRunner() || productToursFlag- const surveysFlag = useToolbarFeatureFlag('surveys-toolbar')- const showSurveys = surveysFlag-const fieldNotesFlag = useToolbarFeatureFlag('field-notes')const showFieldNotes = inStorybook() || inStorybookTestRunner() || fieldNotesFlag@@ -455,8 +442,6 @@ export function ToolbarInfoMenu(): JSX.Element | null {<ProductToursToolbarMenu />) : visibleMenu === 'field-notes' && showFieldNotes ? (<FieldNotesToolbarMenu />- ) : visibleMenu === 'surveys' && showSurveys ? (- <SurveysToolbarMenu />) : nulluseEffect(() => {@@ -515,14 +500,10 @@ export function Toolbar(): JSX.Element | null {const { authenticate, openUiHostConfigModal, closeUiHostConfigModal, closeAuthConfirmModal } =useActions(toolbarConfigLogic)const { selectedTourId, isPreviewing } = useValues(productToursLogic)- const { isCreating: isSurveyCreating } = useValues(surveysToolbarLogic)const productToursFlag = useToolbarFeatureFlag('product-tours-2025')const showProductTours = inStorybook() || inStorybookTestRunner() || productToursFlag- const surveysFlag = useToolbarFeatureFlag('surveys-toolbar')- const showSurveys = surveysFlag-const fieldNotesFlag = useToolbarFeatureFlag('field-notes')const showFieldNotes = inStorybook() || inStorybookTestRunner() || fieldNotesFlagconst { hasOpenedFieldNotes } = useValues(fieldNotesLogic)@@ -570,7 +551,6 @@ export function Toolbar(): JSX.Element | null {<Suspense fallback={null}>{showToursSidebar && <ProductToursSidebar />}{showFieldNotes && <FieldNotesOverlay />}- {isSurveyCreating && <SurveySidebar />}</Suspense><ToolbarInfoMenu /><div@@ -579,14 +559,9 @@ export function Toolbar(): JSX.Element | null {'Toolbar--minimized': minimized,'Toolbar--hedgehog-mode': hedgehogMode,'Toolbar--dragging': isDragging,- 'Toolbar--extra-buttons-1':- 1 + (showProductTours ? 1 : 0) + (showFieldNotes ? 1 : 0) + (showSurveys ? 1 : 0) === 1,- 'Toolbar--extra-buttons-2':- 1 + (showProductTours ? 1 : 0) + (showFieldNotes ? 1 : 0) + (showSurveys ? 1 : 0) === 2,- 'Toolbar--extra-buttons-3':- 1 + (showProductTours ? 1 : 0) + (showFieldNotes ? 1 : 0) + (showSurveys ? 1 : 0) === 3,- 'Toolbar--extra-buttons-4':- 1 + (showProductTours ? 1 : 0) + (showFieldNotes ? 1 : 0) + (showSurveys ? 1 : 0) === 4,+ 'Toolbar--extra-buttons-1': 1 + (showProductTours ? 1 : 0) + (showFieldNotes ? 1 : 0) === 1,+ 'Toolbar--extra-buttons-2': 1 + (showProductTours ? 1 : 0) + (showFieldNotes ? 1 : 0) === 2,+ 'Toolbar--extra-buttons-3': 1 + (showProductTours ? 1 : 0) + (showFieldNotes ? 1 : 0) === 3,})}onMouseDown={(e) => onMouseOrTouchDown(e.nativeEvent)}onTouchStart={(e) => onMouseOrTouchDown(e.nativeEvent)}@@ -662,11 +637,6 @@ export function Toolbar(): JSX.Element | null {<LockableMenuIcon icon={<IconApp />} locked={heatmapGate === 'locked'} /></ToolbarButton>)}- {showSurveys && (- <ToolbarButton menuId="surveys" title="Surveys">- <IconMessage />- </ToolbarButton>- )}</>) : authStatus === 'checking' || authStatus === 'authenticating' ? (<ToolbarButton flex>diff --git a/frontend/src/toolbar/bar/toolbarLogic.ts b/frontend/src/toolbar/bar/toolbarLogic.tsindex 5ea8f60af6c3..6d3e33e51485 100644--- a/frontend/src/toolbar/bar/toolbarLogic.ts+++ b/frontend/src/toolbar/bar/toolbarLogic.ts@@ -15,7 +15,6 @@ import { experimentsTabLogic } from '~/toolbar/experiments/experimentsTabLogic'import { fieldNotesLogic } from '~/toolbar/field-notes/fieldNotesLogic'import { flagsToolbarLogic } from '~/toolbar/flags/flagsToolbarLogic'import { productToursLogic } from '~/toolbar/product-tours/productToursLogic'-import { surveysToolbarLogic } from '~/toolbar/surveys/surveysToolbarLogic'import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'import { isToolbarFeatureGated, toolbarEntitlementsLogic } from '~/toolbar/toolbarEntitlementsLogic'import { toolbarLogger } from '~/toolbar/toolbarLogger'@@ -45,7 +44,6 @@ export type MenuState =| 'experiments'| 'web-vitals'| 'product-tours'- | 'surveys'| 'field-notes'export type ToolbarPositionType =@@ -69,7 +67,6 @@ export interface toolbarLogicValues {isRefreshing: boolean // heatmapToolbarMenuLogicrawHeatmapLoading: boolean // heatmapToolbarMenuLogichedgehogMode: HedgehogModeInterface | null // hedgehogModeLogic- allSurveysLoading: boolean // surveysToolbarLogicposthog: PostHog | null // toolbarConfigLogicremoteWebVitalsLoading: boolean // webVitalsToolbarLogiccspBlocksNewFunction: boolean@@ -187,12 +184,6 @@ export interface toolbarLogicActions {showButtonProductTours: () => {value: true} // productToursLogic- hideButtonSurveys: () => {- value: true- } // surveysToolbarLogic- showButtonSurveys: () => {- value: true- } // surveysToolbarLogiclogout: () => {value: true} // toolbarConfigLogic@@ -341,8 +332,7 @@ export interface toolbarLogicMeta {allActionsLoading: boolean,userFlagsLoading: boolean,allExperimentsLoading: boolean,- remoteWebVitalsLoading: boolean,- allSurveysLoading: boolean+ remoteWebVitalsLoading: boolean) => booleanhedgehogModeAvailable: (cspBlocksNewFunction: boolean) => boolean}@@ -372,8 +362,6 @@ export const toolbarLogic = kea<toolbarLogicType>([['allExperimentsLoading'],webVitalsToolbarLogic,['remoteWebVitalsLoading'],- surveysToolbarLogic,- ['allSurveysLoading'],hedgehogModeLogic,['hedgehogMode'],],@@ -396,8 +384,6 @@ export const toolbarLogic = kea<toolbarLogicType>([['showButtonProductTours', 'hideButtonProductTours'],fieldNotesLogic,['showButtonFieldNotes', 'hideButtonFieldNotes'],- surveysToolbarLogic,- ['showButtonSurveys', 'hideButtonSurveys'],heatmapToolbarMenuLogic,['enableHeatmap',@@ -754,7 +740,6 @@ export const toolbarLogic = kea<toolbarLogicType>([s.userFlagsLoading,s.allExperimentsLoading,s.remoteWebVitalsLoading,- s.allSurveysLoading,],(elementStatsLoading: boolean,@@ -763,8 +748,7 @@ export const toolbarLogic = kea<toolbarLogicType>([allActionsLoading: boolean,userFlagsLoading: boolean,allExperimentsLoading: boolean,- remoteWebVitalsLoading: boolean,- allSurveysLoading: boolean+ remoteWebVitalsLoading: boolean) =>elementStatsLoading ||rawHeatmapLoading ||@@ -772,8 +756,7 @@ export const toolbarLogic = kea<toolbarLogicType>([allActionsLoading ||userFlagsLoading ||allExperimentsLoading ||- remoteWebVitalsLoading ||- allSurveysLoading,+ remoteWebVitalsLoading,],hedgehogModeAvailable: [(s) => [s.cspBlocksNewFunction],@@ -821,7 +804,6 @@ export const toolbarLogic = kea<toolbarLogicType>([actions.hideButtonActions()actions.hideButtonProductTours()actions.hideButtonFieldNotes()- actions.hideButtonSurveys()if (visibleMenu === 'heatmap') {if (!isToolbarFeatureGated(AvailableFeature.TOOLBAR_HEATMAPS, 'toolbar-paid-heatmaps')) {@@ -839,8 +821,6 @@ export const toolbarLogic = kea<toolbarLogicType>([actions.showButtonProductTours()} else if (visibleMenu === 'field-notes') {actions.showButtonFieldNotes()- } else if (visibleMenu === 'surveys') {- actions.showButtonSurveys()}},diff --git a/frontend/src/toolbar/surveys/SurveyListView.tsx b/frontend/src/toolbar/surveys/SurveyListView.tsxdeleted file mode 100644index a73117d8f760..000000000000--- a/frontend/src/toolbar/surveys/SurveyListView.tsx+++ /dev/null@@ -1,78 +0,0 @@-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.tsxdeleted file mode 100644index cdfbd7c83d5d..000000000000--- a/frontend/src/toolbar/surveys/SurveyLivePreview.tsx+++ /dev/null@@ -1,102 +0,0 @@-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.tsxdeleted file mode 100644index 195feb5cad87..000000000000--- a/frontend/src/toolbar/surveys/SurveyRow.tsx+++ /dev/null@@ -1,65 +0,0 @@-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 { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'-import { urls } from '~/toolbar/urls'-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.tsxdeleted file mode 100644index ddde2610462d..000000000000--- a/frontend/src/toolbar/surveys/SurveySidebar.tsx+++ /dev/null@@ -1,584 +0,0 @@-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 { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'-import { urls } from '~/toolbar/urls'-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.tsxdeleted file mode 100644index 0607d8a80425..000000000000--- a/frontend/src/toolbar/surveys/SurveysToolbarMenu.tsx+++ /dev/null@@ -1,5 +0,0 @@-import { SurveyListView } from './SurveyListView'--export function SurveysToolbarMenu(): JSX.Element {- return <SurveyListView />-}diff --git a/frontend/src/toolbar/surveys/constants.tsx b/frontend/src/toolbar/surveys/constants.tsxdeleted file mode 100644index ae98c886243e..000000000000--- a/frontend/src/toolbar/surveys/constants.tsx+++ /dev/null@@ -1,17 +0,0 @@-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.tsdeleted file mode 100644index 18c2527b0c76..000000000000--- a/frontend/src/toolbar/surveys/surveysToolbarLogic.ts+++ /dev/null@@ -1,806 +0,0 @@-import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea'-import { loaders } from 'kea-loaders'--import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'--import { toolbarLogic } from '~/toolbar/bar/toolbarLogic'-import { toolbarApi } from '~/toolbar/toolbarApi'-import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'-import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'-import { urls } from '~/toolbar/urls'-import { joinWithUiHost } from '~/toolbar/utils'-import {- Survey,- SurveyAppearance,- SurveyMatchType,- SurveyPosition,- SurveyQuestionType,- SurveySchedule,- SurveyType,-} from '~/types'--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'- }- if (survey.end_date) {- return 'complete'- }- 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> {- const result = await toolbarApi.surveys.update(surveyId, payload, {- context: 'update_survey',- toastOnError: 'Failed to update survey',- })- if (!result.ok) {- return false- }- lemonToast.success(successMessage)- return true-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface surveysToolbarLogicValues {- allSurveys: Survey[]- allSurveysLoading: boolean- canProceed: boolean- canProceedReason: string | null- editingSurvey: Survey | null- editingSurveyId: string | null- hasMoreSurveys: boolean- isCreating: boolean- isLifecyclePending: boolean- isSubmitting: boolean- previewSurvey: Survey | null- quickForm: QuickSurveyForm- searchTerm: string-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface surveysToolbarLogicActions {- archiveSurvey: (survey: Survey) => {- survey: Survey- }- cancelQuickCreate: () => {- value: true- }- hideButtonSurveys: () => {- value: true- }- launchSurvey: (survey: Survey) => {- survey: Survey- }- loadMoreSurveys: () => any- loadMoreSurveysFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadMoreSurveysSuccess: (- allSurveys: Survey[],- payload?: any- ) => {- allSurveys: Survey[]- payload?: any- }- loadSurveys: () => any- loadSurveysFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadSurveysSuccess: (- allSurveys: Survey[],- payload?: any- ) => {- allSurveys: Survey[]- payload?: any- }- resumeSurvey: (survey: Survey) => {- survey: Survey- }- setFormField: (- field: keyof QuickSurveyForm,- value: unknown- ) => {- field: keyof QuickSurveyForm- value: unknown- }- setHasMoreSurveys: (hasMore: boolean) => {- hasMore: boolean- }- setLifecyclePending: (pending: boolean) => {- pending: boolean- }- setSearchTerm: (searchTerm: string) => {- searchTerm: string- }- showButtonSurveys: () => {- value: true- }- startQuickCreate: () => {- value: true- }- startQuickEdit: (survey: Survey) => {- survey: Survey- }- stopSurvey: (survey: Survey) => {- survey: Survey- }- submitQuickCreate: (launch?: boolean) => {- launch: boolean- }- submitQuickCreateFailure: () => {- value: true- }- submitQuickCreateSuccess: () => {- value: true- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface surveysToolbarLogicMeta {- __keaTypeGenInternalSelectorTypes: {- previewSurvey: (quickForm: QuickSurveyForm, isCreating: boolean, editingSurvey: Survey | null) => Survey | null- canProceed: (quickForm: QuickSurveyForm) => boolean- canProceedReason: (quickForm: QuickSurveyForm) => string | null- }-}--export type surveysToolbarLogicType = MakeLogicType<- surveysToolbarLogicValues,- surveysToolbarLogicActions,- Record<string, any>,- surveysToolbarLogicMeta->--export const surveysToolbarLogic = kea<surveysToolbarLogicType>([- path(['toolbar', 'surveys', 'surveysToolbarLogic']),-- actions({- 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, actions }) => ({- allSurveys: [- [] as Survey[],- {- loadSurveys: async () => {- const search = values.searchTerm- const result = await toolbarApi.surveys.list(- { limit: SURVEYS_PAGE_SIZE, offset: 0, search: search || undefined },- { context: 'load_surveys' }- )- // 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 (!result.ok) {- actions.setHasMoreSurveys(false)- return []- }- actions.setHasMoreSurveys(!!result.data.next)- return result.data.results ?? []- },- 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 result = await toolbarApi.surveys.list(- { limit: SURVEYS_PAGE_SIZE, offset: values.allSurveys.length, search: search || undefined },- { context: 'load_more_surveys' }- )- // Search changed while we were paging — drop the result.- if (search !== values.searchTerm) {- return values.allSurveys- }- if (!result.ok) {- return values.allSurveys- }- actions.setHasMoreSurveys(!!result.data.next)- const newRows: Survey[] = (result.data.results ?? []).filter((s: Survey) => !previousIds.has(s.id))- return [...values.allSurveys, ...newRows]- },- },- ],- })),-- reducers({- searchTerm: [- '',- {- 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: QuickSurveyForm, isCreating: boolean, editingSurvey: Survey | null): 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: QuickSurveyForm): 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: QuickSurveyForm): 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, 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- }- const result = editingId- ? await toolbarApi.surveys.update(editingId, payload, {- context: 'save_survey',- toastOnError: 'Failed to save survey',- })- : await toolbarApi.surveys.create(payload, {- context: 'create_survey',- toastOnError: 'Failed to create survey',- })- // If the user cancelled while we were awaiting, drop the result- // silently — they explicitly threw the work away.- if (!values.isCreating) {- return- }- if (!result.ok) {- actions.submitQuickCreateFailure()- return- }- const saved = result.data- 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()- },- })),-])diff --git a/frontend/src/toolbar/toolbarApi.ts b/frontend/src/toolbar/toolbarApi.tsindex 3cf63234f996..5dbdf65bb730 100644--- a/frontend/src/toolbar/toolbarApi.ts+++ b/frontend/src/toolbar/toolbarApi.ts@@ -7,13 +7,13 @@ import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'import { toolbarFetch } from '~/toolbar/toolbarFetch'import { toolbarLogger } from '~/toolbar/toolbarLogger'import type { ElementsEventType, WebExperiment } from '~/toolbar/types'-import type { ActionType, CombinedFeatureFlagAndValueType, EventDefinition, ProductTour, Survey } from '~/types'+import type { ActionType, CombinedFeatureFlagAndValueType, EventDefinition, ProductTour } from '~/types'/*** The single, blessed way to talk to the PostHog API from the toolbar.** Every authenticated data request should go through `toolbarApi` — preferably one of its- * resource namespaces (`toolbarApi.actions.list()`, `toolbarApi.surveys.update(id, …)`), which+ * resource namespaces (`toolbarApi.actions.list()`, `toolbarApi.productTours.delete(id, …)`), which* own the route strings (see the `toolbarApi` export below for the full contract). It wraps* `toolbarFetch` (which owns the OAuth bearer + token refresh) and folds the eight different* ad-hoc failure-handling styles the toolbar had grown into one consistent contract:@@ -236,7 +236,7 @@ const ENVIRONMENT = '/api/environments/@current'/*** `toolbarApi` is the single entry point for talking to the PostHog API from the toolbar.*- * Prefer the resource namespaces (`toolbarApi.actions.list()`, `toolbarApi.surveys.update(id, …)`):+ * Prefer the resource namespaces (`toolbarApi.actions.list()`, `toolbarApi.productTours.delete(id, …)`):* they own the route strings so every `/api/projects/@current/…` path lives in exactly one place* and call sites read as intent rather than URLs. Each method takes the resource-specific arguments* (id, payload, query) plus a `ToolbarApiOptions` and returns the same `ToolbarApiResult<T>`, so@@ -299,23 +299,6 @@ export const toolbarApi = {apiDelete(`${PROJECT}/field_notes/${id}/`, options),},- surveys: {- list: (- params: { limit: number; offset: number; search?: string },- options: ToolbarApiOptions- ): Promise<ToolbarApiResult<{ results?: Survey[]; next?: string | null }>> =>- apiGet(`${PROJECT}/surveys/${encodeParams({ archived: false, ...params }, '?')}`, options),- create: (- payload: Record<string, any>,- options: ToolbarApiOptions- ): Promise<ToolbarApiResult<{ id?: string }>> => apiPost(`${PROJECT}/surveys/`, payload, options),- update: (- id: number | string,- payload: Record<string, any>,- options: ToolbarApiOptions- ): Promise<ToolbarApiResult<{ id?: string }>> => apiPatch(`${PROJECT}/surveys/${id}/`, payload, options),- },-featureFlags: {myFlags: (params: Record<string, any>,diff --git a/frontend/src/toolbar/urls.test.ts b/frontend/src/toolbar/urls.test.tsindex 0e5558388adf..91cb66d92156 100644--- a/frontend/src/toolbar/urls.test.ts+++ b/frontend/src/toolbar/urls.test.ts@@ -19,8 +19,6 @@ describe('toolbar urls duplicate', () => {productTour: [['tour-id'], ['tour-id', 'step=2'], ['tour-id', '?step=2']],sessionProfile: [['session-uuid']],settings: [[], ['project'], ['environment-customization', 'date-and-time'], ['user']],- survey: [['survey-uuid'], ['new']],- surveys: [[], ['archived']],webAnalyticsWebVitals: [[]],}diff --git a/frontend/src/toolbar/urls.ts b/frontend/src/toolbar/urls.tsindex 1a22c748544a..b198d01be41f 100644--- a/frontend/src/toolbar/urls.ts+++ b/frontend/src/toolbar/urls.ts@@ -31,8 +31,6 @@ export const urls = {sessionProfile: (id: string): string => `/sessions/${id}`,settings: (section: string = 'project', setting?: string): string =>combineUrl(`/settings/${section}`, undefined, setting).url,- survey: (id: string): string => `/surveys/${id}`,- surveys: (tab?: string): string => `/surveys${tab ? `?tab=${tab}` : ''}`,webAnalyticsWebVitals: (): string => `/web/web-vitals`,}diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 66048d722380..1f9f893cc400 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1293,8 +1293,6 @@ TOOLBAR_OAUTH_SCOPES = ["heatmap:write","element:read","uploaded_media:write",- "survey:read",- "survey:write","field_note:read","field_note:write",]