Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(surveys): Add question html support #17847

Merged
merged 4 commits into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified frontend/__snapshots__/scenes-app-surveys--new-survey.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
87 changes: 81 additions & 6 deletions frontend/src/scenes/surveys/Survey.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import { Form, Group } from 'kea-forms'
import { PageHeader } from 'lib/components/PageHeader'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import {
LemonBanner,
LemonButton,
LemonCheckbox,
LemonCollapse,
LemonDivider,
LemonInput,
LemonSelect,
LemonTabs,
LemonTextArea,
Link,
} from '@posthog/lemon-ui'
Expand All @@ -36,6 +38,7 @@ import { featureFlagLogic } from 'scenes/feature-flags/featureFlagLogic'
import { defaultSurveyFieldValues, defaultSurveyAppearance, NewSurvey, SurveyUrlMatchTypeLabels } from './constants'
import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagReleaseConditions } from 'scenes/feature-flags/FeatureFlagReleaseConditions'
import { CodeEditor } from 'lib/components/CodeEditors'
import { NotFound } from 'lib/components/NotFound'

export const scene: SceneExport = {
Expand Down Expand Up @@ -68,9 +71,16 @@ export function SurveyComponent({ id }: { id?: string } = {}): JSX.Element {
}

export function SurveyForm({ id }: { id: string }): JSX.Element {
const { survey, surveyLoading, isEditingSurvey, hasTargetingFlag, urlMatchTypeValidationError } =
useValues(surveyLogic)
const { loadSurvey, editingSurvey, setSurveyValue, setDefaultForQuestionType } = useActions(surveyLogic)
const {
survey,
surveyLoading,
isEditingSurvey,
hasTargetingFlag,
urlMatchTypeValidationError,
writingHTMLDescription,
} = useValues(surveyLogic)
const { loadSurvey, editingSurvey, setSurveyValue, setDefaultForQuestionType, setWritingHTMLDescription } =
useActions(surveyLogic)
const { featureFlags } = useValues(enabledFeaturesLogic)

return (
Expand Down Expand Up @@ -153,7 +163,7 @@ export function SurveyForm({ id }: { id: string }): JSX.Element {
</div>
),
content: (
<>
<div className="space-y-2">
<Field name="type" label="Question type" className="max-w-60">
<LemonSelect
onSelect={(newType) => {
Expand Down Expand Up @@ -208,7 +218,72 @@ export function SurveyForm({ id }: { id: string }): JSX.Element {
</Field>
)}
<Field name="description" label="Question description (optional)">
<LemonTextArea value={question.description || ''} minRows={2} />
{({ value, onChange }) => (
<>
<LemonTabs
activeKey={writingHTMLDescription ? 'html' : 'text'}
onChange={(key) =>
setWritingHTMLDescription(key === 'html')
}
tabs={[
{
key: 'text',
label: (
<span className="text-sm">Text</span>
),
content: (
<LemonTextArea
data-attr="survey-description"
minRows={2}
value={value}
onChange={(v) => onChange(v)}
/>
),
},
{
key: 'html',
label: (
<span className="text-sm">HTML</span>
),
content: (
<div>
<CodeEditor
className="border"
language="html"
value={value}
onChange={(v) =>
onChange(v ?? '')
}
height={150}
options={{
minimap: { enabled: false },
wordWrap: 'on',
scrollBeyondLastLine: false,
automaticLayout: true,
fixedOverflowWidgets: true,
lineNumbers: 'off',
glyphMargin: false,
folding: false,
}}
/>
</div>
),
},
]}
/>
{question.description &&
question.description
?.toLowerCase()
.includes('<script') && (
<LemonBanner type="warning">
Scripts won't run in the survey popup and
we'll remove these on save. Use the API
question mode to run your own scripts in
surveys.
</LemonBanner>
)}
</>
)}
</Field>
{question.type === SurveyQuestionType.Rating && (
<div className="flex flex-col gap-2">
Expand Down Expand Up @@ -323,7 +398,7 @@ export function SurveyForm({ id }: { id: string }): JSX.Element {
</Field>
</div>
)}
</>
</div>
),
},
]}
Expand Down
8 changes: 7 additions & 1 deletion frontend/src/scenes/surveys/SurveyAppearance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { useValues } from 'kea'
import { useEffect, useRef, useState } from 'react'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { sanitize } from 'dompurify'

interface SurveyAppearanceProps {
type: SurveyQuestionType
Expand Down Expand Up @@ -270,7 +271,12 @@ function BaseAppearance({
</div>
<div className="question-textarea-wrapper">
<div className="survey-question">{question}</div>
{description && <div className="description">{description}</div>}
{/* Using dangerouslySetInnerHTML is safe here, because it's taking the user's input and showing it to the same user.
They can try passing in arbitrary scripts, but it would show up only for them, so it's like trying to XSS yourself, where
you already have all the data. Furthermore, sanitization should catch all obvious attempts */}
{description && (
<div className="description" dangerouslySetInnerHTML={{ __html: sanitize(description) }} />
)}
{type === SurveyQuestionType.Open && (
<textarea
style={{
Expand Down
32 changes: 28 additions & 4 deletions frontend/src/scenes/surveys/surveyLogic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
NEW_SURVEY,
NewSurvey,
} from './constants'
import { sanitize } from 'dompurify'

export interface SurveyLogicProps {
id: string | 'new'
Expand Down Expand Up @@ -94,6 +95,7 @@ export const surveyLogic = kea<surveyLogicType>([
}),
archiveSurvey: true,
setCurrentQuestionIndexAndType: (idx: number, type: SurveyQuestionType) => ({ idx, type }),
setWritingHTMLDescription: (writingHTML: boolean) => ({ writingHTML }),
}),
loaders(({ props, actions, values }) => ({
survey: {
Expand All @@ -110,11 +112,11 @@ export const surveyLogic = kea<surveyLogicType>([
}
return { ...NEW_SURVEY }
},
createSurvey: async (surveyPayload) => {
return await api.surveys.create(surveyPayload)
createSurvey: async (surveyPayload: Partial<Survey>) => {
return await api.surveys.create(sanitizeQuestions(surveyPayload))
},
updateSurvey: async (surveyPayload) => {
return await api.surveys.update(props.id, surveyPayload)
updateSurvey: async (surveyPayload: Partial<Survey>) => {
return await api.surveys.update(props.id, sanitizeQuestions(surveyPayload))
},
launchSurvey: async () => {
const startDate = dayjs()
Expand Down Expand Up @@ -259,6 +261,12 @@ export const surveyLogic = kea<surveyLogicType>([
setCurrentQuestionIndexAndType: (_, { idx, type }) => ({ idx, type }),
},
],
writingHTMLDescription: [
false,
{
setWritingHTMLDescription: (_, { writingHTML }) => writingHTML,
},
],
}),
selectors({
isSurveyRunning: [
Expand Down Expand Up @@ -514,3 +522,19 @@ export const surveyLogic = kea<surveyLogicType>([
}
}),
])

function sanitizeQuestions(surveyPayload: Partial<Survey>): Partial<Survey> {
if (!surveyPayload.questions) {
return surveyPayload
}
return {
...surveyPayload,
questions: surveyPayload.questions?.map((rawQuestion) => {
return {
...rawQuestion,
description: sanitize(rawQuestion.description || ''),
question: sanitize(rawQuestion.question || ''),
}
}),
}
}
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@
"d3": "^7.8.2",
"d3-sankey": "^0.12.3",
"dayjs": "^1.10.7",
"dompurify": "^3.0.6",
"esbuild": "^0.14.54",
"esbuild-plugin-less": "^1.1.7",
"esbuild-sass-plugin": "^1.8.2",
Expand Down Expand Up @@ -201,6 +202,7 @@
"@types/clone": "^2.1.1",
"@types/d3": "^7.4.0",
"@types/d3-sankey": "^0.12.1",
"@types/dompurify": "^3.0.3",
"@types/image-blob-reduce": "^4.1.1",
"@types/jest": "^29.2.3",
"@types/jest-image-snapshot": "^6.1.0",
Expand Down
22 changes: 21 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 32 additions & 0 deletions posthog/api/survey.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@

from posthog.utils_cors import cors_response

import nh3

SURVEY_TARGETING_FLAG_PREFIX = "survey-targeting-"


Expand Down Expand Up @@ -87,6 +89,36 @@ class Meta:
]
read_only_fields = ["id", "linked_flag", "targeting_flag", "created_at"]

def validate_questions(self, value):
if value is None:
return value

if not isinstance(value, list):
raise serializers.ValidationError("Questions must be a list of objects")

cleaned_questions = []
for raw_question in value:
if not isinstance(raw_question, dict):
raise serializers.ValidationError("Questions must be a list of objects")

cleaned_question = {
**raw_question,
}
question_text = raw_question.get("question")

if not question_text:
raise serializers.ValidationError("Question text is required")

description = raw_question.get("description")
if nh3.is_html(question_text):
cleaned_question["question"] = nh3.clean(question_text)
if description and nh3.is_html(description):
cleaned_question["description"] = nh3.clean(description)

cleaned_questions.append(cleaned_question)

return cleaned_questions

def validate(self, data):
linked_flag_id = data.get("linked_flag_id")
if linked_flag_id:
Expand Down
Loading
Loading