Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(surveys): preserve branching when adding, moving, or deleting questions (#58510)

Lucas Faria071e829e2707
diff --git a/frontend/src/scenes/surveys/SurveyEdit.tsx b/frontend/src/scenes/surveys/SurveyEdit.tsx
index 9d5470355f72..31d14d7fa624 100644
--- a/frontend/src/scenes/surveys/SurveyEdit.tsx
+++ b/frontend/src/scenes/surveys/SurveyEdit.tsx
@@ -288,6 +288,7 @@ export default function SurveyEdit({ id }: { id: string }): JSX.Element {
setEditingLanguage,
setFlagPropertyErrors,
deleteBranchingLogic,
+ moveQuestion,
setSurveyManualErrors,
editingSurvey,
loadSurvey,
@@ -337,16 +338,7 @@ export default function SurveyEdit({ id }: { id: string }): JSX.Element {
}
function onSortEnd({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }): void {
- function move(arr: SurveyQuestion[], from: number, to: number): SurveyQuestion[] {
- const clone = [...arr]
- // Remove the element from the array
- const [element] = clone.splice(from, 1)
- // Insert the element at the new position
- clone.splice(to, 0, element)
- return clone.map((child) => ({ ...child }))
- }
-
- setSurveyValue('questions', move(survey.questions, oldIndex, newIndex))
+ moveQuestion(oldIndex, newIndex)
setSelectedPageIndex(newIndex)
}
@@ -738,37 +730,10 @@ export default function SurveyEdit({ id }: { id: string }): JSX.Element {
<DndContext
onDragEnd={({ active, over }) => {
if (over && active.id !== over.id) {
- const finishDrag = (): void =>
- onSortEnd({
- oldIndex: sortedItemIds.indexOf(active.id.toString()),
- newIndex: sortedItemIds.indexOf(over.id.toString()),
- })
-
- if (hasBranchingLogic) {
- LemonDialog.open({
- title: 'Your survey has active branching logic',
- description: (
- <p className="py-2">
- Rearranging questions will remove your branching
- logic. Are you sure you want to continue?
- </p>
- ),
-
- primaryButton: {
- children: 'Continue',
- status: 'danger',
- onClick: () => {
- deleteBranchingLogic()
- finishDrag()
- },
- },
- secondaryButton: {
- children: 'Cancel',
- },
- })
- } else {
- finishDrag()
- }
+ onSortEnd({
+ oldIndex: sortedItemIds.indexOf(active.id.toString()),
+ newIndex: sortedItemIds.indexOf(over.id.toString()),
+ })
}
}}
>
@@ -800,7 +765,6 @@ export default function SurveyEdit({ id }: { id: string }): JSX.Element {
index={index}
survey={survey}
setSelectedPageIndex={setSelectedPageIndex}
- setSurveyValue={setSurveyValue}
translationValidationErrors={
activeTranslationValidationErrors
}
diff --git a/frontend/src/scenes/surveys/SurveyEditQuestionRow.tsx b/frontend/src/scenes/surveys/SurveyEditQuestionRow.tsx
index 9f11f5ff2b5f..f5b85608a8a8 100644
--- a/frontend/src/scenes/surveys/SurveyEditQuestionRow.tsx
+++ b/frontend/src/scenes/surveys/SurveyEditQuestionRow.tsx
@@ -33,7 +33,6 @@ type SurveyQuestionHeaderProps = {
index: number
survey: Survey | NewSurvey
setSelectedPageIndex: (index: number) => void
- setSurveyValue: (key: string, value: any) => void
translationValidationErrors?: Array<{ language: string; questionIndex: number; field: string; error: string }>
translationErrorsByQuestion?: (
questionIndex: number
@@ -55,11 +54,10 @@ export function SurveyEditQuestionHeader({
index,
survey,
setSelectedPageIndex,
- setSurveyValue,
translationErrorsByQuestion,
}: SurveyQuestionHeaderProps): JSX.Element {
- const { hasBranchingLogic, editingLanguage } = useValues(surveyLogic)
- const { deleteBranchingLogic } = useActions(surveyLogic)
+ const { editingLanguage } = useValues(surveyLogic)
+ const { removeQuestion } = useActions(surveyLogic)
const { setNodeRef, attributes, transform, transition, listeners, isDragging } = useSortable({
id: index.toString(),
})
@@ -104,39 +102,9 @@ export function SurveyEditQuestionHeader({
size="xsmall"
data-attr={`delete-survey-question-${index}`}
onClick={(e) => {
- const deleteQuestion = (): void => {
- e.stopPropagation()
- setSelectedPageIndex(index <= 0 ? 0 : index - 1)
- setSurveyValue(
- 'questions',
- survey.questions.filter((_, i) => i !== index)
- )
- }
-
- if (hasBranchingLogic) {
- LemonDialog.open({
- title: 'Your survey has active branching logic',
- description: (
- <p className="py-2">
- Deleting the question will remove your branching logic. Are you sure you
- want to continue?
- </p>
- ),
- primaryButton: {
- children: 'Continue',
- status: 'danger',
- onClick: () => {
- deleteBranchingLogic()
- deleteQuestion()
- },
- },
- secondaryButton: {
- children: 'Cancel',
- },
- })
- } else {
- deleteQuestion()
- }
+ e.stopPropagation()
+ setSelectedPageIndex(index <= 0 ? 0 : index - 1)
+ removeQuestion(index)
}}
tooltipPlacement="top-end"
/>
diff --git a/frontend/src/scenes/surveys/components/question-branching/utils.test.ts b/frontend/src/scenes/surveys/components/question-branching/utils.test.ts
index c4257f52cdc1..600048068429 100644
--- a/frontend/src/scenes/surveys/components/question-branching/utils.test.ts
+++ b/frontend/src/scenes/surveys/components/question-branching/utils.test.ts
@@ -3,6 +3,8 @@ import { SurveyQuestion, SurveyQuestionBranchingType, SurveyQuestionType } from
import {
SPECIFIC_QUESTION_SEPARATOR,
branchingConfigToDropdownValue,
+ buildDeleteIndexMap,
+ buildReorderIndexMap,
canQuestionHaveResponseBasedBranching,
createBranchingConfig,
createSpecificQuestionValue,
@@ -11,6 +13,7 @@ import {
isSpecificQuestionValue,
isValidBranchingType,
parseSpecificQuestionValue,
+ remapBranchingIndices,
} from './utils'
describe('branching utils', () => {
@@ -285,4 +288,138 @@ describe('branching utils', () => {
})
})
})
+
+ describe('buildReorderIndexMap', () => {
+ it.each([
+ // Move forward: [A,B,C,D] -> [B,C,A,D]
+ ['forward (oldIndex < newIndex)', 4, 0, 2, [2, 0, 1, 3]],
+ // Move backward: [A,B,C,D] -> [A,D,B,C]
+ ['backward (oldIndex > newIndex)', 4, 3, 1, [0, 2, 3, 1]],
+ // No-op when oldIndex === newIndex
+ ['identity when oldIndex === newIndex', 3, 1, 1, [0, 1, 2]],
+ // Swap last two
+ ['adjacent swap forward', 3, 1, 2, [0, 2, 1]],
+ ])('builds the index map for %s', (_label, length, oldIndex, newIndex, expected) => {
+ expect(buildReorderIndexMap(length, oldIndex, newIndex)).toEqual(expected)
+ })
+ })
+
+ describe('buildDeleteIndexMap', () => {
+ it.each([
+ ['middle deletion', 4, 1, [0, null, 1, 2]],
+ ['deletion at the start', 3, 0, [null, 0, 1]],
+ ['deletion at the end', 3, 2, [0, 1, null]],
+ ['single-item array', 1, 0, [null]],
+ ])('builds the index map for %s', (_label, length, deletedIndex, expected) => {
+ expect(buildDeleteIndexMap(length, deletedIndex)).toEqual(expected)
+ })
+ })
+
+ describe('remapBranchingIndices', () => {
+ const ratingQuestionAt = (branching: SurveyQuestion['branching']): SurveyQuestion =>
+ ({
+ type: SurveyQuestionType.Rating,
+ question: 'rate',
+ display: 'number',
+ scale: 10,
+ lowerBoundLabel: 'low',
+ upperBoundLabel: 'high',
+ branching,
+ }) as SurveyQuestion
+
+ const plainOpenQuestion: SurveyQuestion = {
+ type: SurveyQuestionType.Open,
+ question: 'open',
+ } as SurveyQuestion
+
+ it('returns questions unchanged when no branching is present', () => {
+ const questions = [plainOpenQuestion, plainOpenQuestion]
+ expect(remapBranchingIndices(questions, [0, 1])).toEqual(questions)
+ })
+
+ it('remaps SpecificQuestion.index on reorder', () => {
+ // Q0 points to Q2; after moving Q2 to position 0: Q0 (now at 1) points to Q2 (now at 0)
+ const original = [
+ ratingQuestionAt({ type: SurveyQuestionBranchingType.SpecificQuestion, index: 2 }),
+ plainOpenQuestion,
+ plainOpenQuestion,
+ ]
+ const reordered = [original[2], original[0], original[1]]
+ const indexMap = buildReorderIndexMap(3, 2, 0)
+ const result = remapBranchingIndices(reordered, indexMap)
+ expect(result[1].branching).toEqual({
+ type: SurveyQuestionBranchingType.SpecificQuestion,
+ index: 0,
+ })
+ })
+
+ it('remaps ResponseBased.responseValues integer targets on reorder', () => {
+ const original = [
+ ratingQuestionAt({
+ type: SurveyQuestionBranchingType.ResponseBased,
+ responseValues: { detractors: 2, passives: 1, promoters: SurveyQuestionBranchingType.End },
+ }),
+ plainOpenQuestion,
+ plainOpenQuestion,
+ ]
+ // Swap Q1 and Q2 (move index 1 to index 2). indexMap = [0, 2, 1].
+ // detractors (was -> 2) becomes 1; passives (was -> 1) becomes 2; promoters stays End.
+ const indexMap = buildReorderIndexMap(3, 1, 2)
+ const result = remapBranchingIndices(original, indexMap)
+ expect(result[0].branching).toEqual({
+ type: SurveyQuestionBranchingType.ResponseBased,
+ responseValues: { detractors: 1, passives: 2, promoters: SurveyQuestionBranchingType.End },
+ })
+ })
+
+ it('drops SpecificQuestion branching when the target was deleted', () => {
+ const original = [
+ ratingQuestionAt({ type: SurveyQuestionBranchingType.SpecificQuestion, index: 1 }),
+ plainOpenQuestion,
+ ]
+ const filtered = [original[0]]
+ const indexMap = buildDeleteIndexMap(2, 1)
+ const result = remapBranchingIndices(filtered, indexMap)
+ expect(result[0].branching).toBeUndefined()
+ })
+
+ it('drops the entire ResponseBased branching when every numeric target was deleted', () => {
+ // Q0 routes detractors -> 1 and passives -> 2; both targets are then deleted.
+ const original = [
+ ratingQuestionAt({
+ type: SurveyQuestionBranchingType.ResponseBased,
+ responseValues: { detractors: 1, passives: 2 },
+ }),
+ plainOpenQuestion,
+ plainOpenQuestion,
+ ]
+ // Delete index 1, then index 2 ... easier to just build the indexMap manually:
+ // both 1 and 2 are removed, only Q0 survives at index 0.
+ const filtered = [original[0]]
+ const indexMap = [0, null, null]
+ const result = remapBranchingIndices(filtered, indexMap)
+ // No surviving rules — fall back to default (no branching) rather than
+ // an empty ResponseBased shell.
+ expect(result[0].branching).toBeUndefined()
+ })
+
+ it('drops a single responseValues mapping when its target was deleted but keeps others', () => {
+ const original = [
+ ratingQuestionAt({
+ type: SurveyQuestionBranchingType.ResponseBased,
+ responseValues: { detractors: 2, passives: 1, promoters: SurveyQuestionBranchingType.End },
+ }),
+ plainOpenQuestion,
+ plainOpenQuestion,
+ ]
+ // Delete index 1 -> indexMap [0, null, 1]; questions array becomes [Q0, Q2]
+ const filtered = [original[0], original[2]]
+ const indexMap = buildDeleteIndexMap(3, 1)
+ const result = remapBranchingIndices(filtered, indexMap)
+ expect(result[0].branching).toEqual({
+ type: SurveyQuestionBranchingType.ResponseBased,
+ responseValues: { detractors: 1, promoters: SurveyQuestionBranchingType.End },
+ })
+ })
+ })
})
diff --git a/frontend/src/scenes/surveys/components/question-branching/utils.ts b/frontend/src/scenes/surveys/components/question-branching/utils.ts
index f9fef360e99e..adb85c4f873c 100644
--- a/frontend/src/scenes/surveys/components/question-branching/utils.ts
+++ b/frontend/src/scenes/surveys/components/question-branching/utils.ts
@@ -134,3 +134,123 @@ export function createBranchingConfig(
throw new Error(`Unknown branching type: ${branchingType}`)
}
}
+
+/**
+ * Remaps branching indices when the question array is mutated (reordered or deleted).
+ *
+ * `indexMap[oldIndex]` is the new position of the question that used to be at
+ * `oldIndex`, or `null` if it was removed. Any branching that pointed at a removed
+ * question is converted to default "Next question" (i.e. `branching` is dropped).
+ *
+ * Adding a question at the end is a no-op since existing indices stay valid.
+ */
+export function remapBranchingIndices(questions: SurveyQuestion[], indexMap: (number | null)[]): SurveyQuestion[] {
+ const remapIndex = (index: number): number | null => {
+ if (index < 0 || index >= indexMap.length) {
+ return null
+ }
+ return indexMap[index]
+ }
+
+ return questions.map((question) => {
+ if (!question.branching) {
+ return question
+ }
+
+ if (question.branching.type === SurveyQuestionBranchingType.SpecificQuestion) {
+ const remapped = remapIndex(question.branching.index)
+ if (remapped === null) {
+ // Target was deleted — fall back to default (Next question / End).
+ const { branching, ...rest } = question
+ return rest as SurveyQuestion
+ }
+ if (remapped === question.branching.index) {
+ return question
+ }
+ return {
+ ...question,
+ branching: { ...question.branching, index: remapped },
+ }
+ }
+
+ if (
+ question.branching.type === SurveyQuestionBranchingType.ResponseBased &&
+ 'responseValues' in question.branching &&
+ question.branching.responseValues
+ ) {
+ const originalEntries = Object.entries(question.branching.responseValues)
+ const nextResponseValues: Record<string, number | SurveyQuestionBranchingType> = {}
+ let changed = false
+ for (const [response, target] of originalEntries) {
+ if (typeof target === 'number') {
+ const remapped = remapIndex(target)
+ if (remapped === null) {
+ // Target was deleted — drop the mapping so it falls back to default.
+ changed = true
+ continue
+ }
+ if (remapped !== target) {
+ changed = true
+ }
+ nextResponseValues[response] = remapped
+ } else {
+ nextResponseValues[response] = target
+ }
+ }
+ if (!changed) {
+ return question
+ }
+ // If we had mappings before and none survived, drop the whole branching block
+ // so the question falls back to default routing (rather than keeping a
+ // dangling ResponseBased config with empty rules).
+ if (originalEntries.length > 0 && Object.keys(nextResponseValues).length === 0) {
+ const { branching, ...rest } = question
+ return rest as SurveyQuestion
+ }
+ return {
+ ...question,
+ branching: { ...question.branching, responseValues: nextResponseValues },
+ }
+ }
+
+ return question
+ })
+}
+
+/**
+ * Builds an index map for a reorder operation that moved a single question
+ * from `oldIndex` to `newIndex` within an array of `length` items.
+ */
+export function buildReorderIndexMap(length: number, oldIndex: number, newIndex: number): (number | null)[] {
+ const map: (number | null)[] = Array.from({ length })
+ for (let i = 0; i < length; i++) {
+ if (i === oldIndex) {
+ map[i] = newIndex
+ } else if (oldIndex < newIndex && i > oldIndex && i <= newIndex) {
+ map[i] = i - 1
+ } else if (oldIndex > newIndex && i >= newIndex && i < oldIndex) {
+ map[i] = i + 1
+ } else {
+ map[i] = i
+ }
+ }
+ return map
+}
+
+/**
+ * Builds an index map for a deletion at `deletedIndex` within an array of `length`
+ * items. The deleted position maps to `null`; later positions shift left by one.
+ */
+export function buildDeleteIndexMap(length: number, deletedIndex: number): (number | null)[] {
+ const map: (number | null)[] = Array.from({ length })
+ for (let i = 0; i < length; i++) {
+ if (i === deletedIndex) {
+ map[i] = null
+ } else if (i > deletedIndex) {
+ map[i] = i - 1
+ } else {
+ map[i] = i
+ }
+ }
+ return map
+}
diff --git a/frontend/src/scenes/surveys/surveyLogic.tsx b/frontend/src/scenes/surveys/surveyLogic.tsx
index d59f6df07ed7..bce5de169148 100644
--- a/frontend/src/scenes/surveys/surveyLogic.tsx
+++ b/frontend/src/scenes/surveys/surveyLogic.tsx
@@ -17,9 +17,12 @@ import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
import { Scene } from 'scenes/sceneTypes'
import {
branchingConfigToDropdownValue,
+ buildDeleteIndexMap,
+ buildReorderIndexMap,
canQuestionHaveResponseBasedBranching,
createBranchingConfig,
getDefaultBranchingType,
+ remapBranchingIndices,
} from 'scenes/surveys/components/question-branching/utils'
import { getDemoDataForSurvey } from 'scenes/surveys/utils/demoDataGenerator'
import { teamLogic } from 'scenes/teamLogic'
@@ -666,6 +669,8 @@ export const surveyLogic = kea<surveyLogicType>([
}),
resetBranchingForQuestion: (questionIndex) => ({ questionIndex }),
deleteBranchingLogic: true,
+ moveQuestion: (oldIndex: number, newIndex: number) => ({ oldIndex, newIndex }),
+ removeQuestion: (questionIndex: number) => ({ questionIndex }),
archiveSurvey: true,
setWritingHTMLDescription: (writingHTML: boolean) => ({ writingHTML }),
setSelectedPageIndex: (idx: number | null) => ({ idx }),
@@ -1785,6 +1790,27 @@ export const surveyLogic = kea<surveyLogicType>([
questions: newQuestions,
}
},
+ moveQuestion: (state, { oldIndex, newIndex }) => {
+ if (oldIndex === newIndex) {
+ return state
+ }
+ const reordered = [...state.questions]
+ const [moved] = reordered.splice(oldIndex, 1)
+ reordered.splice(newIndex, 0, moved)
+ const indexMap = buildReorderIndexMap(state.questions.length, oldIndex, newIndex)
+ return {
+ ...state,
+ questions: remapBranchingIndices(reordered, indexMap),
+ }
+ },
+ removeQuestion: (state, { questionIndex }) => {
+ const filtered = state.questions.filter((_, i) => i !== questionIndex)
+ const indexMap = buildDeleteIndexMap(state.questions.length, questionIndex)
+ return {
+ ...state,
+ questions: remapBranchingIndices(filtered, indexMap),
+ }
+ },
},
],
selectedPageIndex: [
diff --git a/frontend/src/scenes/surveys/wizard/steps/QuestionsStep.tsx b/frontend/src/scenes/surveys/wizard/steps/QuestionsStep.tsx
index 83733e1a91bb..25bc3ad41176 100644
--- a/frontend/src/scenes/surveys/wizard/steps/QuestionsStep.tsx
+++ b/frontend/src/scenes/surveys/wizard/steps/QuestionsStep.tsx
@@ -516,7 +516,7 @@ interface QuestionsStepProps {
export function QuestionsStep({ editingLanguage, setEditingLanguage }: QuestionsStepProps): JSX.Element {
const { survey } = useValues(surveyLogic)
- const { setSurveyValue } = useActions(surveyLogic)
+ const { setSurveyValue, moveQuestion, removeQuestion } = useActions(surveyLogic)
const { selectedTemplate } = useValues(surveyWizardLogic)
const { restoreDefaultQuestions } = useActions(surveyWizardLogic)
@@ -534,8 +534,7 @@ export function QuestionsStep({ editingLanguage, setEditingLanguage }: Questions
}
const deleteQuestion = (index: number): void => {
- const newQuestions = questions.filter((_, i) => i !== index)
- setSurveyValue('questions', newQuestions)
+ removeQuestion(index)
}
const addQuestion = (type: SurveyQuestionType): void => {
@@ -572,11 +571,7 @@ export function QuestionsStep({ editingLanguage, setEditingLanguage }: Questions
if (over && active.id !== over.id) {
const oldIndex = sortedItemIds.indexOf(active.id.toString())
const newIndex = sortedItemIds.indexOf(over.id.toString())
-
- const newQuestions = [...questions]
- const [removed] = newQuestions.splice(oldIndex, 1)
- newQuestions.splice(newIndex, 0, removed)
- setSurveyValue('questions', newQuestions)
+ moveQuestion(oldIndex, newIndex)
}
}