: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
import { Meta, StoryObj } from '@storybook/react'
import { useDelayedOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { App } from 'scenes/App'
import { SurveysTabs } from 'scenes/surveys/surveysLogic'
import { urls } from 'scenes/urls'
import { mswDecorator, useStorybookMocks } from '~/mocks/browser'
import organizationCurrent from '~/mocks/fixtures/api/organizations/@current/@current.json'
import { toPaginatedResponse } from '~/mocks/handlers'
import {
AccessControlLevel,
FeatureFlagBasicType,
MultipleSurveyQuestion,
PropertyFilterType,
PropertyOperator,
Survey,
SurveyEventName,
SurveyQuestionType,
SurveySchedule,
SurveyType,
} from '~/types'
import { SurveyEditSection, surveyLogic } from './surveyLogic'
const MOCK_BASIC_SURVEY: Survey = {
id: '0187c279-bcae-0000-34f5-4f121921f005',
name: 'basic survey',
description: 'basic survey description',
type: SurveyType.Popover,
created_at: '2023-04-27T10:04:37.977401Z',
created_by: {
id: 1,
uuid: '01863799-062b-0000-8a61-b2842d5f8642',
distinct_id: 'Sopz9Z4NMIfXGlJe6W1XF98GOqhHNui5J5eRe0tBGTE',
first_name: 'Employee 427',
email: '[email protected]',
},
questions: [{ question: 'question 1?', type: SurveyQuestionType.Open }],
conditions: null,
linked_flag: null,
linked_flag_id: null,
targeting_flag: null,
targeting_flag_filters: undefined,
appearance: { backgroundColor: 'white', submitButtonColor: '#2C2C2C' },
start_date: null,
end_date: null,
archived: false,
responses_limit: null,
iteration_count: null,
iteration_frequency_days: null,
schedule: SurveySchedule.Once,
user_access_level: AccessControlLevel.Editor,
}
const MOCK_SURVEY_WITH_MULTIPLE_OPTIONS: Survey = {
id: '998FE805-F9EF-4F25-A5D1-B9549C4E2143',
name: 'survey with multiple options',
description: 'survey with multiple options description',
type: SurveyType.Popover,
created_at: '2023-04-27T10:04:37.977401Z',
created_by: {
id: 1,
uuid: '01863799-062b-0000-8a61-b2842d5f8642',
distinct_id: 'Sopz9Z4NMIfXGlJe6W1XF98GOqhHNui5J5eRe0tBGTE',
first_name: 'Employee 427',
email: '[email protected]',
},
questions: [
{
type: SurveyQuestionType.MultipleChoice,
question: "We're sorry to see you go. What's your reason for unsubscribing?",
choices: [
'I no longer need the product',
'I found a better product',
'I found the product too difficult to use',
'Other',
],
shuffleOptions: true,
},
],
conditions: null,
linked_flag: null,
linked_flag_id: null,
targeting_flag: null,
targeting_flag_filters: undefined,
appearance: { backgroundColor: 'white', submitButtonColor: '#2C2C2C' },
start_date: null,
end_date: null,
archived: false,
responses_limit: null,
iteration_count: null,
iteration_frequency_days: null,
schedule: SurveySchedule.Once,
user_access_level: AccessControlLevel.Editor,
}
const MOCK_SURVEY_WITH_RELEASE_CONS: Survey = {
id: '0187c279-bcae-0000-34f5-4f121921f006',
name: 'survey with release conditions',
description: 'survey with release conditions description',
type: SurveyType.Popover,
created_at: '2023-04-28T10:04:37.977401Z',
created_by: {
id: 1,
uuid: '01863799-062b-0000-8a61-b2842d5f8642',
distinct_id: 'Sopz9Z4NMIfXGlJe6W1XF98GOqhHNui5J5eRe0tBGTE',
first_name: 'Employee 427',
email: '[email protected]',
},
questions: [{ question: 'question 2?', type: SurveyQuestionType.Open }],
appearance: { backgroundColor: 'white', submitButtonColor: '#2C2C2C' },
conditions: {
url: 'posthog',
selector: '',
events: { values: [{ name: 'user_subscribed' }] },
actions: { values: [] },
},
linked_flag: {
id: 7,
team_id: 1,
name: '',
key: 'early-access-feature',
filters: {
groups: [
{
variant: null,
properties: [],
rollout_percentage: undefined,
},
],
payloads: {},
multivariate: null,
},
deleted: false,
active: true,
ensure_experience_continuity: false,
},
linked_flag_id: 7,
targeting_flag: {
id: 15,
team_id: 1,
name: 'Targeting flag for survey survey with release conditions',
key: 'survey-targeting-survey-with-release-conditions',
filters: {
groups: [
{
variant: null,
properties: [
{
key: 'email',
type: PropertyFilterType.Person,
value: ['[email protected]'],
operator: PropertyOperator.Exact,
},
],
rollout_percentage: 100,
},
],
multivariate: null,
payloads: {},
},
deleted: false,
active: true,
ensure_experience_continuity: false,
},
targeting_flag_filters: undefined,
start_date: '2023-04-29T10:04:37.977401Z',
end_date: null,
archived: false,
responses_limit: null,
iteration_count: null,
iteration_frequency_days: null,
schedule: SurveySchedule.Once,
user_access_level: AccessControlLevel.Editor,
}
const MOCK_SURVEY_SHOWN = {
clickhouse:
"SELECT count() AS `survey shown` FROM events WHERE and(equals(events.team_id, 1), equals(events.event, %(hogql_val_0)s), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_1)s), ''), 'null'), '^\"|\"$', ''), %(hogql_val_2)s), 0)) LIMIT 100 SETTINGS readonly=2, max_execution_time=60",
columns: ['survey shown'],
hogql: "SELECT count() AS `survey shown` FROM events WHERE and(equals(event, 'survey shown'), equals(properties.$survey_id, '0188e637-3b72-0000-f407-07a338652af9')) LIMIT 100",
query: "select count() as 'survey shown' from events where event == 'survey shown' and properties.$survey_id == '0187c279-bcae-0000-34f5-4f121921f006'",
results: [[0]],
types: [['survey shown', 'UInt64']],
}
const MOCK_SURVEY_RESULTS = {
columns: ['*', 'properties.$survey_response', 'timestamp', 'person'],
hasMore: false,
results: [],
types: [
"Tuple(UUID, String, String, DateTime64(6, 'UTC'), Int64, String, String, DateTime64(6, 'UTC'))",
'Nullable(String)',
"DateTime64(6, 'UTC')",
'String',
],
}
const MOCK_RESPONSES_COUNT = {
'0187c279-bcae-0000-34f5-4f121921f005': 17,
'0187c279-bcae-0000-34f5-4f121921f006': 25,
}
// Survey whose results actually load, so the question-visualization charts render.
const MOCK_SURVEY_WITH_RESULTS: Survey = {
id: '0187c279-bcae-0000-34f5-4f121921f099',
name: 'survey with results',
description: 'survey whose question charts render',
type: SurveyType.Popover,
created_at: '2023-05-01T10:04:37.977401Z',
created_by: {
id: 1,
uuid: '01863799-062b-0000-8a61-b2842d5f8642',
distinct_id: 'Sopz9Z4NMIfXGlJe6W1XF98GOqhHNui5J5eRe0tBGTE',
first_name: 'Employee 427',
email: '[email protected]',
},
questions: [
{
type: SurveyQuestionType.Rating,
question: 'How likely are you to recommend us to a friend?',
id: 'q-rating',
display: 'number',
scale: 10,
lowerBoundLabel: 'Not likely',
upperBoundLabel: 'Very likely',
},
{
type: SurveyQuestionType.SingleChoice,
question: 'What is your favorite feature?',
id: 'q-single',
choices: ['Dashboards', 'Insights', 'Experiments', 'Surveys'],
},
{
type: SurveyQuestionType.MultipleChoice,
question: "We're sorry to see you go. What's your reason for unsubscribing?",
id: 'q-multi',
choices: [
'I no longer need the product',
'I found a better product',
'I found the product too difficult to use',
'Other',
],
},
],
conditions: null,
linked_flag: null,
linked_flag_id: null,
targeting_flag: null,
targeting_flag_filters: undefined,
appearance: { backgroundColor: 'white', submitButtonColor: '#2C2C2C' },
start_date: '2023-05-02T10:04:37.977401Z',
end_date: null,
archived: false,
responses_limit: null,
iteration_count: null,
iteration_frequency_days: null,
schedule: SurveySchedule.Once,
user_access_level: AccessControlLevel.Editor,
}
// Rows from the consolidated aggregate query: [question_id, label, count].
const MOCK_SURVEY_AGGREGATE_RESULTS = {
columns: ['question_id', 'label', 'cnt'],
types: [
['question_id', 'String'],
['label', 'String'],
['cnt', 'UInt64'],
],
results: [
// Rating (NPS scale 0-10) — mix of detractors / passives / promoters
['q-rating', '10', 32],
['q-rating', '9', 28],
['q-rating', '8', 14],
['q-rating', '7', 9],
['q-rating', '6', 5],
['q-rating', '5', 4],
['q-rating', '3', 2],
['q-rating', '0', 3],
// Single choice
['q-single', 'Dashboards', 30],
['q-single', 'Insights', 25],
['q-single', 'Experiments', 12],
['q-single', 'Surveys', 8],
// Multiple choice (with the synthetic total row the processor expects)
['q-multi', 'I no longer need the product', 20],
['q-multi', 'I found a better product', 15],
['q-multi', 'I found the product too difficult to use', 10],
['q-multi', 'Other', 5],
['q-multi', '__total__', 40],
],
}
// Rows from the base-stats query: [event_name, total_count, unique_persons, first_seen, last_seen].
const MOCK_SURVEY_BASE_STATS = {
columns: ['event_name', 'total_count', 'unique_persons', 'first_seen', 'last_seen', 'outcome_counts'],
types: [
['event_name', 'String'],
['total_count', 'UInt64'],
['unique_persons', 'UInt64'],
['first_seen', "Nullable(DateTime64(6, 'UTC'))"],
['last_seen', "Nullable(DateTime64(6, 'UTC'))"],
['outcome_counts', 'Tuple(UInt64, UInt64, UInt64)'],
],
results: [
[SurveyEventName.SHOWN, 120, 110, '2023-05-02T10:00:00Z', '2023-06-20T10:00:00Z', [0, 0, 0]],
[SurveyEventName.SENT, 75, 70, '2023-05-02T11:00:00Z', '2023-06-20T09:00:00Z', [40, 30, 5]],
[SurveyEventName.DISMISSED, 18, 17, '2023-05-03T10:00:00Z', '2023-06-19T10:00:00Z', [0, 0, 0]],
],
}
const meta: Meta = {
component: App,
title: 'Scenes-App/Surveys',
parameters: {
layout: 'fullscreen',
viewMode: 'story',
mockDate: '2023-06-28', // To stabilize relative dates
pageUrl: urls.surveys(),
},
decorators: [
(Story) => {
// Pin the survey editor preference to the full editor so the
// `/surveys/new` stories don't get redirected to the guided wizard.
localStorage.setItem('scenes.surveys.surveysLogic.preferredEditor', JSON.stringify('full'))
return <Story />
},
mswDecorator({
get: {
'/api/projects/:team_id/surveys/': toPaginatedResponse([
MOCK_BASIC_SURVEY,
MOCK_SURVEY_WITH_RELEASE_CONS,
MOCK_SURVEY_WITH_MULTIPLE_OPTIONS,
]),
'/api/projects/:team_id/surveys/0187c279-bcae-0000-34f5-4f121921f005/': MOCK_BASIC_SURVEY,
'/api/projects/:team_id/surveys/0187c279-bcae-0000-34f5-4f121921f006/': MOCK_SURVEY_WITH_RELEASE_CONS,
'/api/projects/:team_id/surveys/998FE805-F9EF-4F25-A5D1-B9549C4E2143/':
MOCK_SURVEY_WITH_MULTIPLE_OPTIONS,
'/api/projects/:team_id/surveys/responses_count/': MOCK_RESPONSES_COUNT,
[`/api/projects/:team_id/feature_flags/${
(MOCK_SURVEY_WITH_RELEASE_CONS.linked_flag as FeatureFlagBasicType).id
}`]: toPaginatedResponse([MOCK_SURVEY_WITH_RELEASE_CONS.linked_flag]),
[`/api/projects/:team_id/feature_flags/${
(MOCK_SURVEY_WITH_RELEASE_CONS.targeting_flag as FeatureFlagBasicType).id
}`]: toPaginatedResponse([MOCK_SURVEY_WITH_RELEASE_CONS.targeting_flag]),
},
post: {
'/api/environments/:team_id/query/:query_kind/': async ({ request }) => {
const body = (await request.json()) as any
if (body?.query?.query?.includes(MOCK_SURVEY_WITH_RESULTS.id)) {
switch (body.query.tags?.name) {
case 'survey_results_aggregate':
return MOCK_SURVEY_AGGREGATE_RESULTS
case 'survey_base_stats':
return MOCK_SURVEY_BASE_STATS
case 'survey_dismissed_sent_overlap':
return { results: [[5]] }
}
return { results: [] }
}
if (body.kind == 'EventsQuery') {
return [200, MOCK_SURVEY_RESULTS]
}
return [200, MOCK_SURVEY_SHOWN]
},
// flag targeting has loaders, make sure they don't keep loading
'/api/projects/:team_id/feature_flags/user_blast_radius/': () => [200, { affected: 120, total: 2000 }],
},
}),
],
}
export default meta
type Story = StoryObj<{}>
export const SurveysList: Story = {}
export const SurveysGlobalSettings: Story = {
parameters: {
pageUrl: urls.surveys(SurveysTabs.Settings),
},
}
export const NewSurvey: Story = {
parameters: {
pageUrl: urls.survey('new'),
},
}
export const NewSurveyCustomisationSection: Story = {
render: () => {
useDelayedOnMountEffect(() => {
surveyLogic({ id: 'new' }).mount()
surveyLogic({ id: 'new' }).actions.setSelectedSection(SurveyEditSection.Customization)
})
return <App />
},
parameters: { pageUrl: urls.survey('new') },
}
export const NewMultiQuestionSurveySection: Story = {
render: () => {
useDelayedOnMountEffect(() => {
surveyLogic({ id: 'new' }).mount()
surveyLogic({ id: 'new' }).actions.setSelectedSection(SurveyEditSection.Steps)
surveyLogic({ id: 'new' }).actions.setSurveyValue('questions', [
{
type: SurveyQuestionType.MultipleChoice,
question: "We're sorry to see you go. What's your reason for unsubscribing?",
choices: [
'I no longer need the product',
'I found a better product',
'I found the product too difficult to use',
'Other',
],
} as MultipleSurveyQuestion,
])
})
return <App />
},
parameters: { pageUrl: urls.survey('new') },
}
export const NewSurveyPresentationSection: Story = {
render: () => {
useDelayedOnMountEffect(() => {
surveyLogic({ id: 'new' }).mount()
surveyLogic({ id: 'new' }).actions.setSelectedSection(SurveyEditSection.Presentation)
})
return <App />
},
parameters: { pageUrl: urls.survey('new') },
tags: ['test-skip'],
}
export const NewSurveyTargetingSection: Story = {
render: () => {
useDelayedOnMountEffect(() => {
surveyLogic({ id: 'new' }).mount()
surveyLogic({ id: 'new' }).actions.setSelectedSection(SurveyEditSection.DisplayConditions)
surveyLogic({ id: 'new' }).actions.setSurveyValue('conditions', { url: 'kiki' })
surveyLogic({ id: 'new' }).actions.setSurveyValue('targeting_flag_filters', {
groups: [
{
properties: [{ key: '$browser', value: ['Chrome'], operator: 'exact', type: 'person' }],
rollout_percentage: 20,
},
],
})
})
return <App />
},
parameters: {
pageUrl: urls.survey('new?edit=true'),
testOptions: {
// The right-hand survey preview is rendered asynchronously by posthog-js after a
// delayed mount, and re-renders as the story sets survey values. Wait for the
// question content inside the form (not just the form shell) so it isn't captured blank.
waitForSelector: [
'.LemonBanner .LemonIcon',
'.TaxonomicPropertyFilter__row',
'.survey-form .survey-question',
],
},
},
}
export const NewSurveyAppearanceSection: Story = {
render: () => {
useDelayedOnMountEffect(() => {
surveyLogic({ id: 'new' }).mount()
surveyLogic({ id: 'new' }).actions.setSelectedSection(SurveyEditSection.Appearance)
})
return <App />
},
parameters: { pageUrl: urls.survey('new?edit=true') },
tags: ['test-skip'],
}
export const NewSurveyWithHTMLQuestionDescription: Story = {
render: () => {
useStorybookMocks({
get: {
// TODO: setting available featues should be a decorator to make this easy
'/api/users/@me': () => [
200,
{
email: '[email protected]',
first_name: 'Test Hedgehog',
organization: {
...organizationCurrent,
available_product_features: [
{
key: 'surveys_text_html',
name: 'surveys_text_html',
},
],
},
},
],
},
})
useDelayedOnMountEffect(() => {
surveyLogic({ id: 'new' }).mount()
surveyLogic({ id: 'new' }).actions.setSelectedSection(SurveyEditSection.Steps)
surveyLogic({ id: 'new' }).actions.setSurveyValue('questions', [
{
type: SurveyQuestionType.Open,
question: 'What is your favorite color?',
description: '<strong>This description has HTML in it</strong>',
descriptionContentType: 'html',
},
])
})
return <App />
},
parameters: {
pageUrl: urls.survey('new?edit=true'),
testOptions: {
waitForSelector: '.survey-question-description strong',
},
},
}
export const NewSurveyWithTextQuestionDescriptionThatDoesNotRenderHTML: Story = {
render: () => {
useDelayedOnMountEffect(() => {
surveyLogic({ id: 'new' }).mount()
surveyLogic({ id: 'new' }).actions.setSelectedSection(SurveyEditSection.Steps)
surveyLogic({ id: 'new' }).actions.setSurveyValue('questions', [
{
type: SurveyQuestionType.Open,
question: 'What is your favorite color?',
description: '<strong>This description has HTML in it</strong>',
descriptionContentType: 'text',
},
])
})
return <App />
},
parameters: {
pageUrl: urls.survey('new?edit=true'),
testOptions: {
waitForSelector: '.survey-question-description',
},
},
}
export const SurveyView: Story = {
tags: ['test-skip'], // FIXME: Fix the mocked data so that survey results can actually load
parameters: {
pageUrl: urls.survey(MOCK_SURVEY_WITH_RELEASE_CONS.id),
},
}
export const SurveyResults: Story = {
parameters: {
pageUrl: urls.survey(MOCK_SURVEY_WITH_RESULTS.id),
testOptions: {
waitForSelector: '[data-attr="survey-rating"] canvas',
},
},
decorators: [
mswDecorator({
get: {
[`/api/projects/:team_id/surveys/${MOCK_SURVEY_WITH_RESULTS.id}/`]: MOCK_SURVEY_WITH_RESULTS,
[`/api/projects/:team_id/surveys/${MOCK_SURVEY_WITH_RESULTS.id}/archived-response-uuids/`]: [],
'/api/projects/:team_id/surveys/responses_count/': {
...MOCK_RESPONSES_COUNT,
[MOCK_SURVEY_WITH_RESULTS.id]: 75,
},
'/api/environments/:team_id/hog_functions/': { count: 0, results: [], next: null },
},
}),
],
}
export const SurveySummaryExport: Story = {
...SurveyResults,
parameters: {
...SurveyResults.parameters,
pageUrl: `${urls.survey(MOCK_SURVEY_WITH_RESULTS.id)}?tab=summary`,
testOptions: {
waitForSelector: '#survey-responses-export',
viewport: { width: 560, height: 800 },
},
},
}
export const SurveyNotFound: Story = {
tags: ['test-skip'],
parameters: {
pageUrl: urls.survey('1234566789'),
},
}