Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/eight-moose-bathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"posthog-android-surveys-compose": patch
---

Honor survey shuffleOptions in the built-in choice UI, keeping Other last and the display order stable while answering.
4 changes: 4 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ jobs:
if: needs.detect-markdown-only.outputs.markdown_only != 'true'
run: make compile

- name: Test survey interactions
if: needs.detect-markdown-only.outputs.markdown_only != 'true'
run: make testSurveyUI

- name: Check release tasks and dependency locks
if: needs.detect-markdown-only.outputs.markdown_only != 'true'
run: make checkRelease
Expand Down
6 changes: 6 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,9 @@ checkRelease:
updateLocks:
./gradlew build :posthog-android-gradle-plugin:build --write-locks
CI=false ./gradlew publishToMavenLocal :posthog-android-gradle-plugin:publishToMavenLocal --write-locks

.PHONY: testSurveyUI

# Compose interaction tests require the debug variant, which CI otherwise skips.
testSurveyUI:
CI=false ./gradlew :posthog-android-surveys-compose:testDebugUnitTest
9 changes: 9 additions & 0 deletions posthog-android-surveys-compose/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ android {
}
}

testOptions {
unitTests.isIncludeAndroidResources = true
}

buildFeatures {
compose = true
}
Expand Down Expand Up @@ -88,7 +92,12 @@ dependencies {
implementation("androidx.compose.ui:ui-tooling-preview")
debugImplementation("androidx.compose.ui:ui-tooling")

debugImplementation("androidx.compose.ui:ui-test-manifest")

// tests
testImplementation("androidx.test.ext:junit:${PosthogBuildConfig.Dependencies.ANDROIDX_JUNIT}")
testImplementation("org.robolectric:robolectric:${PosthogBuildConfig.Dependencies.ROBOLECTRIC}")
testImplementation("androidx.compose.ui:ui-test-junit4")
testImplementation("junit:junit:${PosthogBuildConfig.Dependencies.ANDROIDX_JUNIT}")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit:${PosthogBuildConfig.Kotlin.KOTLIN}")
}
Expand Down
65 changes: 58 additions & 7 deletions posthog-android-surveys-compose/gradle.lockfile

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
Expand All @@ -34,27 +35,32 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import com.posthog.android.surveys.compose.internal.theme.localAppearance
import com.posthog.surveys.PostHogDisplayChoiceQuestion

/**
* Shared list-of-choices renderer for [SingleChoice] and [MultipleChoice].
*
* Each option is a rounded bordered button that turns bold + checkmark-decorated
* when selected. When [hasOpenChoice] is true the last option is treated as an
* when selected. When [PostHogDisplayChoiceQuestion.hasOpenChoice] is true the last option is treated as an
* "other"-style free-text input that becomes editable while selected.
*/
@Composable
internal fun ChoiceOptions(
options: List<String>,
hasOpenChoice: Boolean,
allowsMultipleSelection: Boolean,
question: PostHogDisplayChoiceQuestion,
selectedOptions: Set<String>,
onSelectedOptionsChange: (Set<String>) -> Unit,
openChoiceInput: String,
onOpenChoiceInputChange: (String) -> Unit,
) {
val options = question.choices
val displayOrder =
rememberSaveable(question.id, options.size, question.hasOpenChoice, question.shuffleOptions) {
surveyChoiceOrder(options, question.hasOpenChoice, question.shuffleOptions)
}
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
options.forEachIndexed { index, option ->
val isOpenChoice = hasOpenChoice && index == options.lastIndex
displayOrder.forEach { index ->
val option = options[index]
val isOpenChoice = question.hasOpenChoice && index == options.lastIndex
val isSelected = option in selectedOptions
ChoiceOption(
option = option,
Expand All @@ -66,7 +72,7 @@ internal fun ChoiceOptions(
val newSelected =
when {
isSelected -> selectedOptions - option
allowsMultipleSelection -> selectedOptions + option
question.isMultipleChoice -> selectedOptions + option
else -> setOf(option)
}
onSelectedOptionsChange(newSelected)
Expand Down Expand Up @@ -166,3 +172,18 @@ private fun ChoiceOption(
}
}
}

internal fun surveyChoiceOrder(
options: List<String>,
hasOpenChoice: Boolean,
shuffleOptions: Boolean,
): List<Int> {
val indices = options.indices.toList()
if (!shuffleOptions) return indices
val regular = if (hasOpenChoice) indices.dropLast(1) else indices
val shuffled = regular.shuffled().toMutableList()
// Match web: avoid the original display order when the random shuffle leaves it unchanged.
if (shuffled.map { options[it] } == regular.map { options[it] }) shuffled.reverse()
if (hasOpenChoice && options.isNotEmpty()) shuffled.add(options.lastIndex)
return shuffled
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,7 @@ internal fun MultipleChoice(
onOpenChoiceInputChange: (String) -> Unit,
) {
ChoiceOptions(
options = question.choices,
hasOpenChoice = question.hasOpenChoice,
allowsMultipleSelection = true,
question = question,
selectedOptions = selectedChoices,
onSelectedOptionsChange = onSelectedChoicesChange,
openChoiceInput = openChoiceInput,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@ internal fun SingleChoice(
) {
val selectedSet = selectedChoice?.let { setOf(it) } ?: emptySet()
ChoiceOptions(
options = question.choices,
hasOpenChoice = question.hasOpenChoice,
allowsMultipleSelection = false,
question = question,
selectedOptions = selectedSet,
onSelectedOptionsChange = { newSet -> onSelectedChoiceChange(newSet.firstOrNull()) },
openChoiceInput = openChoiceInput,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.posthog.android.surveys.compose.internal.ui

import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals

@RunWith(Parameterized::class)
internal class SurveyChoiceOrderTest(private val hasOpenChoice: Boolean) {
@Test
fun `disabled shuffle preserves configured order`() {
assertEquals(listOf(0, 1, 2), surveyChoiceOrder(listOf("A", "B", "Other"), hasOpenChoice, false))
}

@Test
fun `shuffle preserves every choice identity and pins Other`() {
val choices = listOf("A", "B", "C", "Other")
val order = surveyChoiceOrder(choices, hasOpenChoice, true)
assertEquals(choices.indices.toList(), order.sorted())
assertNotEquals(choices.indices.toList(), order)
if (hasOpenChoice) assertEquals(choices.lastIndex, order.last())
}

@Test
fun `two regular choices always swap matching web fallback`() {
val choices = if (hasOpenChoice) listOf("A", "B", "Other") else listOf("A", "B")
assertEquals(if (hasOpenChoice) listOf(1, 0, 2) else listOf(1, 0), surveyChoiceOrder(choices, hasOpenChoice, true))
}

@Test
fun `small and duplicate lists retain every original index`() {
for (choices in listOf(emptyList(), listOf("Other"), listOf("A", "Other"), listOf("A", "A", "Other"))) {
val order = surveyChoiceOrder(choices, hasOpenChoice, true)
assertEquals(choices.indices.toList(), order.sorted())
if (hasOpenChoice && choices.isNotEmpty()) assertEquals(choices.lastIndex, order.last())
}
}

companion object {
@JvmStatic
@Parameterized.Parameters(name = "open={0}")
fun cases(): List<Array<Boolean>> = listOf(arrayOf(false), arrayOf(true))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package com.posthog.android.surveys.compose.internal.ui

import androidx.compose.material3.MaterialTheme
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.hasSetTextAction
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTextInput
import com.posthog.surveys.PostHogDisplayChoiceQuestion
import com.posthog.surveys.PostHogDisplaySurvey
import com.posthog.surveys.PostHogDisplaySurveyAppearance
import com.posthog.surveys.PostHogDisplaySurveyTextContentType
import com.posthog.surveys.PostHogNextSurveyQuestion
import com.posthog.surveys.PostHogSurveyResponse
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.ParameterizedRobolectricTestRunner
import org.robolectric.annotation.Config
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals

@RunWith(ParameterizedRobolectricTestRunner::class)
@Config(sdk = [28])
internal class SurveyShuffleInteractionTest(
private val isMultipleChoice: Boolean,
private val hasOpenChoice: Boolean,
private val shouldShuffleOptions: Boolean,
) {
@get:Rule val compose = createComposeRule()

@Test
fun `display order stays stable through selection and submits the displayed answer`() {
val choices = listOf("A", "B", "C") + if (hasOpenChoice) listOf("Other") else emptyList()
val labels = choices.map { if (hasOpenChoice && it == "Other") "Other:" else it }
val responses = mutableListOf<PostHogSurveyResponse>()
val survey =
PostHogDisplaySurvey(
id = "shouldShuffleOptions",
name = "Shuffle",
questions = listOf(question("First", choices), question("Last", listOf("Done"))),
appearance = PostHogDisplaySurveyAppearance(displayThankYouMessage = false),
)
compose.setContent {
MaterialTheme {
SurveySheet(survey, onSurveyShown = {}, onSubmit = { _, response ->
responses.add(response)
PostHogNextSurveyQuestion(1, false)
}, onClose = {})
}
}

fun visibleOrder() = labels.sortedBy { compose.onNodeWithText(it).fetchSemanticsNode().boundsInRoot.top }
val order = visibleOrder()
if (shouldShuffleOptions) assertNotEquals(labels, order) else assertEquals(labels, order)
if (hasOpenChoice) assertEquals("Other:", order.last())

compose.onNodeWithText("B").performClick()
assertEquals(order, visibleOrder())
if (hasOpenChoice) {
compose.onNodeWithText("Other:").performClick()
compose.onNode(hasSetTextAction()).performTextInput("Custom answer")
assertEquals(order, visibleOrder())
}
compose.onNodeWithText("Submit").performClick()
compose.onNodeWithText("Last").assertIsDisplayed()
compose.onNodeWithText("Done").assertIsDisplayed()
compose.runOnIdle {
assertEquals(listOf(expectedResponse()), responses)
}
}

private fun expectedResponse(): PostHogSurveyResponse =
if (isMultipleChoice) {
PostHogSurveyResponse.MultipleChoice(if (hasOpenChoice) listOf("B", "Custom answer") else listOf("B"))
} else {
PostHogSurveyResponse.SingleChoice(if (hasOpenChoice) "Custom answer" else "B")
}

private fun question(
id: String,
choices: List<String>,
) = PostHogDisplayChoiceQuestion(
id = id, question = id, questionDescription = null,
questionDescriptionContentType = PostHogDisplaySurveyTextContentType.TEXT,
isOptional = false, buttonText = "Submit", choices = choices,
hasOpenChoice = hasOpenChoice && id == "First", shuffleOptions = shouldShuffleOptions, isMultipleChoice = isMultipleChoice,
)

companion object {
@JvmStatic
@ParameterizedRobolectricTestRunner.Parameters(name = "isMultipleChoice={0}, hasOpenChoice={1}, shouldShuffleOptions={2}")
fun cases(): List<Array<Boolean>> =
listOf(false, true).flatMap { isMultipleChoice ->
listOf(false, true).flatMap {
hasOpenChoice ->
listOf(false, true).map {
shouldShuffleOptions ->
arrayOf(isMultipleChoice, hasOpenChoice, shouldShuffleOptions)
}
}
}
}
}