Composables
Docs Login
Pairel

Discover

Jetpack Compose Screen

Download
package com.composables.pairel

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.VectorConverter
import androidx.compose.animation.core.animate
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.movableContentOf
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.composables.pairel.components.AppBar
import com.composables.pairel.components.Button
import com.composables.pairel.components.Icon
import com.composables.pairel.components.IconButton
import com.composables.pairel.components.ScreenScaffold
import com.composables.pairel.components.Tag
import com.composables.pairel.components.TagVariant
import com.composables.pairel.components.Text
import com.composables.pairel.theme.Check
import com.composables.pairel.theme.Heart
import com.composables.pairel.theme.Icons
import com.composables.pairel.theme.SlidersHorizontal
import com.composables.pairel.theme.Theme
import com.composables.pairel.theme.X
import com.composables.systembars.SystemBarContent
import com.composables.systembars.SystemBars
import com.composables.uripainter.rememberUriPainter
import com.composeunstyled.DialogPanel
import com.composeunstyled.UnstyledDialog
import kotlin.math.abs
import kotlin.time.Duration.Companion.milliseconds
import kotlinx.coroutines.launch

@Composable
fun DiscoverScreen(
    navigateToProfile: (Person) -> Unit,
    navigateToConversation: (Person) -> Unit,
    navigateToDiscoveryPreferences: () -> Unit,
    navigateToMatches: () -> Unit,
    navigateToMyProfile: () -> Unit,
    modifier: Modifier = Modifier,
) {
    MainNavigationLayout(
        navigationBar = {
            MainNavigationBar(
                selected = MainDestination.Discover,
                navigateToDiscover = {},
                navigateToMatches = navigateToMatches,
                navigateToMyProfile = navigateToMyProfile,
            )
        },
        modifier = modifier,
    ) { contentPadding ->
        DiscoverDestination(
            navigateToProfile,
            navigateToConversation,
            navigateToDiscoveryPreferences,
            contentPadding = contentPadding,
        )
    }
}

@Composable
fun DiscoverDestination(
    navigateToProfile: (Person) -> Unit,
    navigateToConversation: (Person) -> Unit,
    navigateToDiscoveryPreferences: () -> Unit,
    contentPadding: PaddingValues,
    modifier: Modifier = Modifier,
) {
    var currentIndex by rememberSaveable { mutableIntStateOf(0) }
    var match by remember { mutableStateOf<Person?>(null) }
    var matchContent by remember { mutableStateOf<Person?>(null) }
    var hasMatched by rememberSaveable { mutableStateOf(false) }
    var completedSwipes by rememberSaveable { mutableIntStateOf(0) }
    var reveal by remember(currentIndex) { mutableFloatStateOf(0f) }
    val profileCards = remember {
        people.map { person ->
            movableContentOf { cardModifier: Modifier -> ProfileCard(person, cardModifier) }
        }
    }

    val bottomPadding = contentPadding.calculateBottomPadding()

    ScreenScaffold(
        modifier = modifier,
        topBar = {
            AppBar(
                title = { Text("Discover") },
                actions = {
                    IconButton(onClick = navigateToDiscoveryPreferences) {
                        Icon(
                            Icons.SlidersHorizontal,
                            contentDescription = "Discovery preferences",
                            modifier = Modifier.size(24.dp),
                        )
                    }
                },
            )
        },
        overlay = {
            UnstyledDialog(
                visible = match != null,
                onDismissRequest = { match = null },
            ) {
                DialogPanel(
                    modifier = Modifier.fillMaxSize(),
                    paneTitle = "It's a match!",
                    enter =
                        fadeIn(tween(260)) +
                            scaleIn(initialScale = 0.94f, animationSpec = tween(380)),
                    exit =
                        fadeOut(tween(260)) +
                            slideOutVertically(
                                targetOffsetY = { it / 10 },
                                animationSpec = tween(260, easing = FastOutSlowInEasing),
                            ),
                ) {
                    SystemBars(
                        statusBar = SystemBarContent.Light,
                        navigationBar = SystemBarContent.Light,
                    )
                    matchContent?.let { person ->
                        MatchMoment(
                            person,
                            onContinue = { match = null },
                            onConversation = {
                                match = null
                                navigateToConversation(person)
                            },
                        )
                    }
                }
            }
        },
    ) {
        Box(
            Modifier.align(Alignment.Center)
                .padding(start = 8.dp, end = 8.dp, top = 8.dp, bottom = bottomPadding + 8.dp)
                .widthIn(max = 480.dp)
                .fillMaxSize(),
            contentAlignment = Alignment.Center,
        ) {
            if (currentIndex < people.size) {
                // Invisible until the top card is dragged, so screen readers skip it.
                Box(
                    Modifier.fillMaxSize()
                        .clearAndSetSemantics {}
                        .graphicsLayer {
                            alpha = reveal
                            scaleX = 0.93f + 0.07f * reveal
                            scaleY = 0.93f + 0.07f * reveal
                            translationY = (1f - reveal) * 22.dp.toPx()
                        }
                ) {
                    val next = people.getOrNull(currentIndex + 1)
                    if (next != null) profileCards[currentIndex + 1](Modifier.fillMaxSize())
                    else EndOfPile(Modifier.fillMaxSize())
                }
                val current = people[currentIndex]
                key(currentIndex) {
                    SwipeCard(
                        profile = current,
                        profileCard = profileCards[currentIndex],
                        modifier = Modifier.fillMaxSize(),
                        onDragProgress = { reveal = it },
                        onOpenProfile = { navigateToProfile(current) },
                        onSwiped = { liked ->
                            completedSwipes++
                            currentIndex++
                            if (liked && completedSwipes >= 3 && !hasMatched) {
                                hasMatched = true
                                matchContent = current
                                match = current
                            }
                        },
                    )
                }
            } else {
                EndOfPile(Modifier.fillMaxSize())
            }
        }
    }
}

@Composable
private fun EndOfPile(modifier: Modifier = Modifier) {
    Column(
        modifier,
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {
        Text("You're all caught up", style = Theme.typography.headline.copy(fontSize = 26.sp))
        Spacer(Modifier.height(10.dp))
        Text("Check back soon for new people.", color = Theme.colors.onBackgroundMuted)
    }
}

@Composable
private fun SwipeCard(
    profile: Person,
    profileCard: @Composable (Modifier) -> Unit,
    modifier: Modifier = Modifier,
    onDragProgress: (Float) -> Unit,
    onOpenProfile: () -> Unit,
    onSwiped: (Boolean) -> Unit,
) {
    var offset by remember { mutableStateOf(Offset.Zero) }
    var settling by remember { mutableStateOf(false) }
    var cardWidth by remember { mutableIntStateOf(1) }
    val scope = rememberCoroutineScope()

    fun moveTo(value: Offset) {
        offset = value
        onDragProgress((abs(value.x) / (cardWidth * 0.3f)).coerceIn(0f, 1f))
    }

    fun settle(target: Offset, decision: Boolean?) {
        settling = true
        scope.launch {
            animate(Offset.VectorConverter, offset, target, animationSpec = tween(260)) { value, _
                ->
                moveTo(value)
            }
            if (decision == null) {
                settling = false
            } else {
                onSwiped(decision)
            }
        }
    }

    Box(
        modifier
            .onSizeChanged { cardWidth = it.width }
            .graphicsLayer {
                translationX = offset.x
                translationY = offset.y
                rotationZ = (offset.x / size.width * 13f).coerceIn(-13f, 13f)
            }
            .pointerInput(profile.name) {
                detectDragGestures(
                    onDragEnd = {
                        if (!settling) {
                            val threshold = size.width * 0.27f
                            when {
                                offset.x > threshold ->
                                    settle(Offset(size.width * 1.5f, offset.y), true)
                                offset.x < -threshold ->
                                    settle(Offset(-size.width * 1.5f, offset.y), false)
                                else -> settle(Offset.Zero, null)
                            }
                        }
                    },
                    onDragCancel = { if (!settling) settle(Offset.Zero, null) },
                    onDrag = { change, amount ->
                        change.consume()
                        if (!settling) moveTo(offset + amount)
                    },
                )
            }
            .testTag("swipe-card")
            .semantics { contentDescription = "${profile.name}, ${profile.age}" }
    ) {
        profileCard(
            Modifier.fillMaxSize()
                .clickable(
                    interactionSource = remember { MutableInteractionSource() },
                    indication = null,
                    onClickLabel = "View ${profile.name}'s profile",
                    onClick = onOpenProfile,
                )
        )
        val progress = (abs(offset.x) / 130f).coerceIn(0f, 1f)
        if (offset.x > 1f)
            SwipeMark(true, Modifier.align(Alignment.TopStart).padding(24.dp), progress)
        if (offset.x < -1f)
            SwipeMark(false, Modifier.align(Alignment.TopEnd).padding(24.dp), progress)
    }
}

@Composable
private fun SwipeMark(liked: Boolean, modifier: Modifier = Modifier, progress: Float) {
    Box(
        modifier
            .graphicsLayer {
                alpha = progress
                translationX = if (liked) progress * 12f else -progress * 12f
            }
            .size(68.dp)
            .clip(CircleShape)
            .background(Theme.colors.surface)
            .semantics { contentDescription = if (liked) "Like" else "Pass" },
        contentAlignment = Alignment.Center,
    ) {
        Icon(
            imageVector = if (liked) Icons.Check else Icons.X,
            contentDescription = null,
            modifier = Modifier.size(40.dp),
            tint = Theme.colors.onSurface,
        )
    }
}

@Composable
private fun MatchMoment(
    person: Person,
    modifier: Modifier = Modifier,
    onContinue: () -> Unit,
    onConversation: () -> Unit,
) {
    val entrance = remember(person) { Animatable(0f) }
    LaunchedEffect(person) {
        entrance.animateTo(
            1f,
            tween(durationMillis = 480, delayMillis = 90, easing = FastOutSlowInEasing),
        )
    }
    BoxWithConstraints(
        modifier
            .fillMaxSize()
            .background(
                Brush.linearGradient(
                    listOf(Theme.colors.accent, Theme.colors.onBackground, Color(0xFF102B29))
                )
            ),
        contentAlignment = Alignment.Center,
    ) {
        val compact = maxHeight < 500.dp
        val portraitSize = if (compact) 120.dp else 154.dp
        Column(
            Modifier.graphicsLayer {
                    alpha = entrance.value
                    translationY = (1f - entrance.value) * 28.dp.toPx()
                }
                .padding(horizontal = 24.dp, vertical = 12.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            Text(
                "Pairel".uppercase(),
                color = Theme.colors.primary,
                style = Theme.typography.caption.copy(fontSize = 13.sp, letterSpacing = 3.sp),
            )
            Spacer(Modifier.height(if (compact) 7.dp else 18.dp))
            Text(
                "It's a match!",
                color = Theme.colors.background,
                style =
                    Theme.typography.display.copy(
                        fontSize = if (compact) 35.sp else 46.sp,
                        textAlign = TextAlign.Center,
                    ),
            )
            Spacer(Modifier.height(if (compact) 5.dp else 12.dp))
            Text(
                "You and ${person.name} like each other.",
                color = Theme.colors.background.copy(alpha = 0.86f),
                style = Theme.typography.body.copy(textAlign = TextAlign.Center),
            )
            Spacer(Modifier.height(if (compact) 17.dp else 38.dp))
            Box(
                Modifier.size(width = portraitSize * 1.85f, height = portraitSize + 8.dp)
                    .graphicsLayer {
                        scaleX = 0.72f + 0.28f * entrance.value
                        scaleY = 0.72f + 0.28f * entrance.value
                    },
                contentAlignment = Alignment.Center,
            ) {
                MatchPortrait(
                    photoUrl = YourPhotoUrl,
                    modifier =
                        Modifier.align(Alignment.CenterStart)
                            .graphicsLayer { rotationZ = -9f }
                            .size(portraitSize),
                    description = "Your photo",
                )
                MatchPortrait(
                    photoUrl = person.photoUrl,
                    modifier =
                        Modifier.align(Alignment.CenterEnd)
                            .graphicsLayer { rotationZ = 9f }
                            .size(portraitSize),
                    description = "${person.name}'s photo",
                )
                Box(
                    Modifier.align(Alignment.BottomCenter)
                        .size(if (compact) 44.dp else 54.dp)
                        .border(4.dp, Theme.colors.onBackground, CircleShape)
                        .clip(CircleShape)
                        .background(Theme.colors.primary),
                    contentAlignment = Alignment.Center,
                ) {
                    Icon(
                        imageVector = Icons.Heart,
                        contentDescription = null,
                        modifier = Modifier.size(if (compact) 26.dp else 32.dp),
                        tint = Theme.colors.background,
                    )
                }
            }
            Spacer(Modifier.height(if (compact) 12.dp else 20.dp))
            Row(
                Modifier.width(portraitSize * 1.85f),
                horizontalArrangement = Arrangement.SpaceBetween,
            ) {
                val labelStyle = Theme.typography.caption.copy(letterSpacing = 1.sp)
                Text(
                    "You".uppercase(),
                    color = Theme.colors.background.copy(alpha = 0.8f),
                    style = labelStyle,
                )
                Text(
                    person.name.uppercase(),
                    color = Theme.colors.background.copy(alpha = 0.8f),
                    style = labelStyle,
                )
            }
            Spacer(Modifier.height(if (compact) 18.dp else 42.dp))
            Button(onClick = onConversation) { Text("Send a message") }
            Spacer(Modifier.height(8.dp))
            Button(onClick = onContinue) { Text("Keep discovering") }
        }
    }
}

@Composable
private fun MatchPortrait(
    photoUrl: String,
    description: String,
    modifier: Modifier = Modifier,
) {
    Box(
        modifier.border(5.dp, Theme.colors.background, CircleShape).padding(5.dp).clip(CircleShape)
    ) {
        Image(
            painter =
                rememberUriPainter(
                    photoUrl,
                    crossfade = 300.milliseconds,
                    contentScale = ContentScale.Crop,
                ),
            contentDescription = description,
            contentScale = ContentScale.Crop,
            modifier = Modifier.fillMaxSize(),
        )
    }
}

@Composable
private fun ProfileCard(profile: Person, modifier: Modifier = Modifier) {
    Box(modifier.clip(Theme.shapes.large).background(Theme.colors.onBackground)) {
        Image(
            painter =
                rememberUriPainter(
                    profile.photoUrl,
                    crossfade = 300.milliseconds,
                    contentScale = ContentScale.Crop,
                ),
            contentDescription = null,
            contentScale = ContentScale.Crop,
            modifier = Modifier.fillMaxSize(),
        )
        Column(
            Modifier.align(Alignment.BottomStart)
                .fillMaxWidth()
                .background(
                    Brush.verticalGradient(
                        0f to Color.Transparent,
                        0.4f to Color.Black.copy(alpha = 0.6f),
                        1f to Color.Black.copy(alpha = 0.82f),
                    )
                )
                .padding(start = 24.dp, end = 24.dp, bottom = 24.dp, top = 96.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp),
        ) {
            Text(
                "${profile.name}, ${profile.age}",
                color = Color.White,
                style = Theme.typography.headline,
            )
            Text(
                profile.bio,
                color = Color.White.copy(alpha = 0.88f),
                maxLines = 2,
                overflow = TextOverflow.Ellipsis,
            )
            FlowRow(
                modifier = Modifier.padding(top = 4.dp),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                for (interest in profile.interests.take(3)) {
                    Tag(TagVariant.OnPhoto) { Text("${interest.emoji} ${interest.label}") }
                }
            }
        }
    }
}

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.