Composables
Docs Login
Pairel

Profile setup

package com.composables.pairel

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.input.InputTransformation
import androidx.compose.foundation.text.input.TextFieldState
import androidx.compose.foundation.text.input.maxLength
import androidx.compose.foundation.text.input.then
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import com.composables.pairel.components.Button
import com.composables.pairel.components.CenteredAppBar
import com.composables.pairel.components.ChoiceButton
import com.composables.pairel.components.Icon
import com.composables.pairel.components.IconButton
import com.composables.pairel.components.ProgressIndicator
import com.composables.pairel.components.ScreenScaffold
import com.composables.pairel.components.Text
import com.composables.pairel.components.TextField
import com.composables.pairel.theme.ArrowLeft
import com.composables.pairel.theme.Icons
import com.composables.pairel.theme.Theme
import kotlin.time.Clock

private enum class SetupStep {
    PersonalDetails,
    DatingIntent,
    Profile,
    Preferences,
}

data class ProfileSetup(
    val firstName: String,
    val birthday: String,
    val datingIntent: DatingIntent,
    val photos: List<Photo>,
    val bio: String,
    val interests: List<Interest>,
    val preferences: DiscoveryPreferences,
)

@Composable
fun ProfileSetupScreen(
    navigateBack: () -> Unit,
    navigateToDiscover: (ProfileSetup) -> Unit,
    modifier: Modifier = Modifier,
    initialPhotos: List<Photo> = emptyList(),
) {
    var step by remember { mutableStateOf(SetupStep.PersonalDetails) }
    val firstName = remember { TextFieldState() }
    val day = remember { TextFieldState() }
    val month = remember { TextFieldState() }
    val year = remember { TextFieldState() }
    val bio = remember { TextFieldState() }
    val photos = remember(initialPhotos) { mutableStateListOf(*initialPhotos.toTypedArray()) }
    val selectedInterests = remember { mutableStateListOf<Interest>() }
    var datingIntent by remember { mutableStateOf<DatingIntent?>(null) }
    var preferences by remember { mutableStateOf(DiscoveryPreferences()) }
    val scrollState = rememberScrollState()
    LaunchedEffect(step) { scrollState.scrollTo(0) }
    val birthday = "${year.text}-${month.text}-${day.text}"
    val complete =
        when (step) {
            SetupStep.PersonalDetails -> firstName.text.isNotBlank() && validAdultBirthday(birthday)
            SetupStep.DatingIntent -> datingIntent != null
            SetupStep.Profile ->
                photos.isNotEmpty() &&
                    bio.text.isNotBlank() &&
                    bio.text.length <= 300 &&
                    selectedInterests.isNotEmpty()
            SetupStep.Preferences -> true
        }

    ScreenScaffold(
        modifier = modifier,
        topBar = {
            CenteredAppBar(
                title = { Text("Profile setup") },
                navigation = {
                    IconButton(
                        onClick = {
                            if (step == SetupStep.PersonalDetails) navigateBack()
                            else step = SetupStep.entries[step.ordinal - 1]
                        }
                    ) {
                        Icon(
                            Icons.ArrowLeft,
                            contentDescription = "Back",
                            modifier = Modifier.size(24.dp),
                        )
                    }
                },
            )
        },
    ) {
        Column(
            Modifier.fillMaxSize()
                .windowInsetsPadding(
                    WindowInsets.navigationBars
                        .union(WindowInsets.ime)
                        .union(WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal))
                ),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            Column(
                Modifier.weight(1f)
                    .verticalScroll(scrollState)
                    .widthIn(max = 560.dp)
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 16.dp),
                verticalArrangement = Arrangement.spacedBy(20.dp),
            ) {
                ProgressIndicator((step.ordinal + 1) / SetupStep.entries.size.toFloat())
                Text(
                    "Step ${step.ordinal + 1} of ${SetupStep.entries.size}",
                    color = Theme.colors.onBackgroundMuted,
                )
                when (step) {
                    SetupStep.PersonalDetails -> {
                        Text("First, the basics", style = Theme.typography.headline)
                        Text(
                            "Your first name and birthday appear on your profile. You can't change them later.",
                            color = Theme.colors.onBackgroundMuted,
                        )
                        TextField(
                            "First name",
                            firstName,
                            modifier = Modifier.fillMaxWidth().testTag("setup-name"),
                        )
                        Text("Birthday", style = Theme.typography.label)
                        Row(
                            Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.spacedBy(8.dp),
                        ) {
                            val numberKeyboard = KeyboardOptions(keyboardType = KeyboardType.Number)
                            TextField(
                                "Day",
                                day,
                                modifier = Modifier.weight(1f).testTag("setup-birthday-day"),
                                placeholder = "DD",
                                keyboardOptions = numberKeyboard,
                                inputTransformation = digitsOnly(2),
                            )
                            TextField(
                                "Month",
                                month,
                                modifier = Modifier.weight(1f).testTag("setup-birthday-month"),
                                placeholder = "MM",
                                keyboardOptions = numberKeyboard,
                                inputTransformation = digitsOnly(2),
                            )
                            TextField(
                                "Year",
                                year,
                                modifier = Modifier.weight(1.4f).testTag("setup-birthday-year"),
                                placeholder = "YYYY",
                                keyboardOptions = numberKeyboard,
                                inputTransformation = digitsOnly(4),
                            )
                        }
                        Text(
                            "You must be at least 18 to join.",
                            color = Theme.colors.onBackgroundMuted,
                        )
                    }
                    SetupStep.DatingIntent -> {
                        Text("What are you looking for?", style = Theme.typography.headline)
                        Text(
                            "Choose what feels right for you.",
                            color = Theme.colors.onBackgroundMuted,
                        )
                        for ((choice, label) in
                            listOf(
                                DatingIntent.LongTerm to "A long-term relationship",
                                DatingIntent.OpenToEither to "Open to seeing where it goes",
                                DatingIntent.Casual to "Something casual",
                            )) {
                            ChoiceButton(
                                selected = datingIntent == choice,
                                onClick = { datingIntent = choice },
                                modifier = Modifier.fillMaxWidth(),
                            ) {
                                Text(label)
                            }
                        }
                    }
                    SetupStep.Profile -> {
                        Text("Show who you are", style = Theme.typography.headline)
                        Text(
                            "Add a photo, a few words, and what you enjoy.",
                            color = Theme.colors.onBackgroundMuted,
                        )
                        EditablePhotoGrid(photos, modifier = Modifier.fillMaxWidth())
                        TextField(
                            "Bio",
                            bio,
                            modifier = Modifier.fillMaxWidth().testTag("setup-bio"),
                            singleLine = false,
                        )
                        Text(
                            "${bio.text.length} / 300",
                            color =
                                if (bio.text.length > 300) Theme.colors.destructive
                                else Theme.colors.onBackgroundMuted,
                        )
                        InterestPicker(selectedInterests, modifier = Modifier.fillMaxWidth())
                    }
                    SetupStep.Preferences -> {
                        Text("Who would you like to meet?", style = Theme.typography.headline)
                        Text(
                            "You can change these anytime.",
                            color = Theme.colors.onBackgroundMuted,
                        )
                        DiscoveryPreferencesForm(
                            preferences = preferences,
                            onPreferencesChange = { preferences = it },
                            modifier = Modifier.fillMaxWidth(),
                            includeDatingIntent = false,
                        )
                    }
                }
            }
            Button(
                onClick = {
                    if (step == SetupStep.Preferences) {
                        navigateToDiscover(
                            ProfileSetup(
                                firstName.text.toString().trim(),
                                birthday,
                                requireNotNull(datingIntent),
                                photos.toList(),
                                bio.text.toString().trim(),
                                selectedInterests.toList(),
                                preferences.copy(datingIntent = requireNotNull(datingIntent)),
                            )
                        )
                    } else step = SetupStep.entries[step.ordinal + 1]
                },
                enabled = complete,
                modifier =
                    Modifier.widthIn(max = 560.dp)
                        .fillMaxWidth()
                        .padding(horizontal = 20.dp, vertical = 16.dp)
                        .testTag("setup-continue"),
            ) {
                Text(if (step == SetupStep.Preferences) "Finish" else "Continue")
            }
        }
    }
}

private fun digitsOnly(maxLength: Int): InputTransformation =
    InputTransformation.maxLength(maxLength).then {
        if (!asCharSequence().all { it.isDigit() }) revertAllChanges()
    }

internal fun validAdultBirthday(
    value: String,
    today: Triple<Int, Int, Int> = utcDateToday(),
): Boolean {
    val parts = value.split('-')
    if (parts.size != 3 || parts[0].length != 4 || parts[1].length != 2 || parts[2].length != 2)
        return false
    val year = parts[0].toIntOrNull() ?: return false
    val month = parts[1].toIntOrNull() ?: return false
    val day = parts[2].toIntOrNull() ?: return false
    if (year < 1900 || month !in 1..12) return false
    val leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
    val days =
        when (month) {
            2 -> if (leap) 29 else 28
            4,
            6,
            9,
            11 -> 30
            else -> 31
        }
    if (day !in 1..days) return false
    val (currentYear, currentMonth, currentDay) = today
    return year < currentYear - 18 ||
        (year == currentYear - 18 &&
            (month < currentMonth || month == currentMonth && day <= currentDay))
}

private fun utcDateToday(): Triple<Int, Int, Int> {
    var days = Clock.System.now().epochSeconds / 86_400
    var year = 1970
    while (days >= if (isLeapYear(year)) 366 else 365) {
        days -= if (isLeapYear(year)) 366 else 365
        year++
    }
    var month = 1
    val monthLengths =
        intArrayOf(31, if (isLeapYear(year)) 29 else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
    while (days >= monthLengths[month - 1]) {
        days -= monthLengths[month - 1]
        month++
    }
    return Triple(year, month, days.toInt() + 1)
}

private fun isLeapYear(year: Int): Boolean = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)

More screens from Pairel

by Alex Styl

Search screens and components

Screen flows

Screens

UI Elements

One Android lesson, every Wednesday

Building Android apps?

What Alex learned building Android apps for 14 years, so you don't have to. Reads in under a minute.

Join 3,500+ Android developers. Unsubscribe any time.

You're subscribed

The next lesson lands in on Wednesday.