Composables
Docs Login
Pairel

Phone verification

package com.composables.pairel

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.aspectRatio
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.BasicTextField
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.mutableIntStateOf
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.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.composables.compose.ripple.rememberRippleIndication
import com.composables.pairel.components.Button
import com.composables.pairel.components.CenteredAppBar
import com.composables.pairel.components.Icon
import com.composables.pairel.components.IconButton
import com.composables.pairel.components.ScreenScaffold
import com.composables.pairel.components.Text
import com.composables.pairel.theme.ArrowLeft
import com.composables.pairel.theme.Icons
import com.composables.pairel.theme.Theme
import kotlinx.coroutines.delay

private const val CodeLength = 6
private const val ResendSeconds = 30

@Composable
fun PhoneVerificationScreen(
    navigateBack: () -> Unit,
    navigateToProfileSetup: () -> Unit,
    navigateToDiscover: () -> Unit,
    modifier: Modifier = Modifier,
    purpose: SignInPurpose = SignInPurpose.CreateAccount,
    phoneNumber: String = "+1 (718) 555-0142",
    expectedCode: String = "246810",
) {
    val code = remember { TextFieldState("") }
    var wrongCode by remember { mutableStateOf(false) }
    var resendRound by remember { mutableIntStateOf(0) }
    var secondsLeft by remember { mutableIntStateOf(ResendSeconds) }
    LaunchedEffect(resendRound) {
        secondsLeft = ResendSeconds
        while (secondsLeft > 0) {
            delay(1000)
            secondsLeft--
        }
    }
    LaunchedEffect(code.text) { wrongCode = false }

    ScreenScaffold(
        modifier = modifier,
        topBar = {
            CenteredAppBar(
                title = { Text("Verify your number") },
                navigation = {
                    IconButton(onClick = navigateBack) {
                        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(rememberScrollState())
                    .widthIn(max = 560.dp)
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 8.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp),
            ) {
                Text("Enter your code", style = Theme.typography.headline)
                Text(
                    "We texted a 6-digit code to $phoneNumber.",
                    color = Theme.colors.onBackgroundMuted,
                )
                CodeInput(
                    state = code,
                    error = wrongCode,
                    modifier = Modifier.fillMaxWidth().padding(top = 12.dp),
                )
                if (wrongCode) {
                    Text(
                        "That code doesn't match. Check the text and try again.",
                        color = Theme.colors.destructive,
                    )
                }
                Column(
                    verticalArrangement = Arrangement.spacedBy(4.dp),
                    modifier = Modifier.padding(top = 4.dp),
                ) {
                    TextAction(
                        label =
                            if (secondsLeft > 0)
                                "Resend code in 0:${secondsLeft.toString().padStart(2, '0')}"
                            else "Resend code",
                        enabled = secondsLeft == 0,
                        onClick = { resendRound++ },
                    )
                    TextAction(label = "Change number", enabled = true, onClick = navigateBack)
                }
            }
            Button(
                onClick = {
                    if (code.text.toString() != expectedCode) {
                        wrongCode = true
                    } else {
                        when (purpose) {
                            SignInPurpose.CreateAccount -> navigateToProfileSetup()
                            SignInPurpose.SignIn -> navigateToDiscover()
                        }
                    }
                },
                enabled = code.text.length == CodeLength,
                modifier =
                    Modifier.widthIn(max = 560.dp)
                        .fillMaxWidth()
                        .padding(horizontal = 20.dp, vertical = 16.dp),
            ) {
                Text("Continue")
            }
        }
    }
}

@Composable
private fun CodeInput(state: TextFieldState, error: Boolean, modifier: Modifier = Modifier) {
    BasicTextField(
        state = state,
        modifier = modifier.semantics { contentDescription = "Verification code" },
        inputTransformation =
            InputTransformation.maxLength(CodeLength).then {
                if (!asCharSequence().all { it.isDigit() }) revertAllChanges()
            },
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),
        decorator = { innerTextField ->
            Box {
                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                    val text = state.text
                    for (index in 0 until CodeLength) {
                        val active = index == text.length
                        Box(
                            Modifier.weight(1f)
                                .aspectRatio(0.85f)
                                .clip(Theme.shapes.small)
                                .background(Theme.colors.surface)
                                .border(
                                    width = if (active || error) 2.dp else 1.dp,
                                    color =
                                        when {
                                            error -> Theme.colors.destructive
                                            active -> Theme.colors.accent
                                            else -> Theme.colors.border
                                        },
                                    shape = Theme.shapes.small,
                                ),
                            contentAlignment = Alignment.Center,
                        ) {
                            Text(
                                text.getOrNull(index)?.toString() ?: "",
                                style =
                                    Theme.typography.title.copy(
                                        fontSize = 24.sp,
                                        lineHeight = 30.sp,
                                    ),
                                color = Theme.colors.onSurface,
                            )
                        }
                    }
                }
                Box(Modifier.size(1.dp).alpha(0f)) { innerTextField() }
            }
        },
    )
}

@Composable
private fun TextAction(
    label: String,
    enabled: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Text(
        label,
        style = Theme.typography.label,
        color = if (enabled) Theme.colors.accent else Theme.colors.onBackgroundMuted,
        modifier =
            modifier
                .clip(Theme.shapes.small)
                .clickable(
                    enabled = enabled,
                    interactionSource = remember { MutableInteractionSource() },
                    indication = rememberRippleIndication(color = Theme.colors.accent),
                    onClick = onClick,
                )
                .padding(horizontal = 8.dp, vertical = 10.dp),
    )
}

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.