Composables
Docs Login
Pairel

Conversation

package com.composables.pairel

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.shrinkVertically
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.detectTapGestures
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.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.height
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.statusBars
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
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.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.layout
import androidx.compose.ui.semantics.CustomAccessibilityAction
import androidx.compose.ui.semantics.customActions
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.unit.dp
import com.composables.compose.ripple.rememberRippleIndication
import com.composables.pairel.components.AlertDialog
import com.composables.pairel.components.Button
import com.composables.pairel.components.ChoiceButton
import com.composables.pairel.components.Icon
import com.composables.pairel.components.IconButton
import com.composables.pairel.components.ModalBottomSheet
import com.composables.pairel.components.ReplyBar
import com.composables.pairel.components.ScreenBackground
import com.composables.pairel.components.ScreenScaffold
import com.composables.pairel.components.Text
import com.composables.pairel.theme.ArrowLeft
import com.composables.pairel.theme.Ellipsis
import com.composables.pairel.theme.Heart
import com.composables.pairel.theme.Icons
import com.composables.pairel.theme.Theme
import com.composables.uripainter.rememberUriPainter
import kotlin.math.roundToInt
import kotlin.time.Duration.Companion.milliseconds
import kotlinx.coroutines.flow.first

private sealed interface MessageContent {
    data class Text(val value: String) : MessageContent

    data class Gif(val description: String, val imageUrl: String) : MessageContent
}

private data class Message(
    val id: Int,
    val content: MessageContent,
    val outgoing: Boolean,
    val hearted: Boolean = false,
)

@Composable
fun ConversationScreen(
    navigateBack: () -> Unit,
    navigateToProfile: (Person) -> Unit,
    navigateToMatches: (unmatched: Person) -> Unit,
    modifier: Modifier = Modifier,
    person: Person = people[0],
) {
    var confirmingUnmatch by remember { mutableStateOf(false) }

    fun unmatch() {
        // unmatch ${person.name} here
        navigateToMatches(person)
    }

    fun reportPerson() {
        // report ${person.name} here
    }

    fun blockPerson() {
        // block ${person.name} here
    }

    var draft by remember(person) { mutableStateOf("") }
    var showOptions by remember { mutableStateOf(false) }
    val messages =
        remember(person) {
            mutableStateListOf(
                Message(0, MessageContent.Text("Hey! Your profile made me smile."), true),
                Message(
                    1,
                    MessageContent.Text(
                        "That's a lovely way to start a conversation. How's your week going?"
                    ),
                    false,
                ),
                Message(2, MessageContent.Text("Pretty well! Any plans for the weekend?"), true),
                Message(
                    3,
                    MessageContent.Text("I'm hunting for the best cinnamon roll in town ๐Ÿฅ"),
                    false,
                ),
                Message(
                    4,
                    MessageContent.Text("That sounds like a very good weekend mission ๐Ÿ˜„"),
                    true,
                ),
                Message(5, MessageContent.Text("Want to join? Coffee's on me โ˜•"), false),
                Message(
                    6,
                    MessageContent.Text("Deal. I'll bring extremely serious pastry opinions ๐Ÿ˜‚"),
                    true,
                ),
                Message(
                    7,
                    MessageContent.Gif(
                        "Happy dance",
                        "https://media.giphy.com/media/xtwLm3wGi8z2qGh5bF/200.gif",
                    ),
                    false,
                ),
            )
        }
    val enteringMessageIds = remember(person) { mutableStateListOf<Int>() }
    val listState = rememberLazyListState()
    val latestMessageId = messages.last().id
    val messageCount = messages.size
    fun send(content: MessageContent) {
        val id = messages.size
        val atLatest =
            listState.firstVisibleItemIndex == 0 && listState.firstVisibleItemScrollOffset == 0
        enteringMessageIds.add(id)
        messages.add(Message(id, content, true))
        // Keep the latest message pinned to the bottom, so the new one grows into view rather
        // than landing off-screen and being scrolled to.
        if (atLatest) listState.requestScrollToItem(0)
    }

    fun toggleHeart(message: Message) {
        // react to the message here
        val index = messages.indexOfFirst { it.id == message.id }
        messages[index] = message.copy(hearted = !message.hearted)
    }

    LaunchedEffect(latestMessageId) {
        if (latestMessageId in enteringMessageIds) {
            snapshotFlow { listState.layoutInfo.totalItemsCount }.first { it >= messageCount }
            if (listState.canScrollBackward || listState.canScrollForward) {
                listState.animateScrollToItem(0)
            }
        }
    }

    ScreenScaffold(modifier = modifier, background = ScreenBackground.Surface) {
        Box(Modifier.fillMaxSize()) {
            Column(
                Modifier.fillMaxSize()
                    .windowInsetsPadding(
                        WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal)
                    )
            ) {
                Box(
                    Modifier.fillMaxWidth()
                        .windowInsetsPadding(WindowInsets.statusBars)
                        .height(104.dp)
                        .padding(horizontal = 16.dp)
                ) {
                    IconButton(
                        onClick = navigateBack,
                        modifier = Modifier.align(Alignment.CenterStart),
                    ) {
                        Icon(
                            Icons.ArrowLeft,
                            contentDescription = "Back",
                            modifier = Modifier.size(24.dp),
                        )
                    }
                    Column(
                        modifier =
                            Modifier.align(Alignment.Center)
                                .clip(Theme.shapes.small)
                                .clickable(
                                    interactionSource = remember { MutableInteractionSource() },
                                    indication =
                                        rememberRippleIndication(color = Theme.colors.onSurface),
                                    onClickLabel = "View ${person.name}'s profile",
                                ) {
                                    navigateToProfile(person)
                                }
                                .padding(horizontal = 12.dp, vertical = 6.dp),
                        horizontalAlignment = Alignment.CenterHorizontally,
                    ) {
                        Image(
                            painter =
                                rememberUriPainter(
                                    person.photoUrl,
                                    crossfade = 300.milliseconds,
                                    contentScale = ContentScale.Crop,
                                ),
                            contentDescription = null,
                            contentScale = ContentScale.Crop,
                            modifier = Modifier.size(44.dp).clip(CircleShape),
                        )
                        Spacer(Modifier.height(4.dp))
                        Text(person.name, style = Theme.typography.label)
                    }
                    IconButton(
                        onClick = { showOptions = true },
                        modifier = Modifier.align(Alignment.CenterEnd),
                    ) {
                        Icon(
                            Icons.Ellipsis,
                            contentDescription = "More options",
                            modifier = Modifier.size(24.dp),
                        )
                    }
                }

                Box(Modifier.weight(1f).fillMaxWidth()) {
                    LazyColumn(
                        modifier = Modifier.fillMaxSize(),
                        state = listState,
                        reverseLayout = true,
                        contentPadding = PaddingValues(16.dp),
                        verticalArrangement = Arrangement.spacedBy(12.dp),
                    ) {
                        items(messages.asReversed(), key = { it.id }) { message ->
                            val entry =
                                remember(message.id) {
                                    Animatable(if (message.id in enteringMessageIds) 0f else 1f)
                                }
                            LaunchedEffect(message.id) {
                                if (message.id in enteringMessageIds) {
                                    entry.animateTo(1f, tween(280, easing = FastOutSlowInEasing))
                                    enteringMessageIds.remove(message.id)
                                }
                            }
                            Row(
                                Modifier.fillMaxWidth().layout { measurable, constraints ->
                                    // Grows from nothing as it enters, so the messages above make
                                    // room smoothly.
                                    val placeable = measurable.measure(constraints)
                                    layout(
                                        placeable.width,
                                        (placeable.height * entry.value).roundToInt(),
                                    ) {
                                        placeable.place(0, 0)
                                    }
                                },
                                horizontalArrangement =
                                    if (message.outgoing) Arrangement.End else Arrangement.Start,
                            ) {
                                Column(
                                    Modifier.graphicsLayer {
                                            alpha = entry.value
                                            translationY = (1f - entry.value) * 18.dp.toPx()
                                        }
                                        .pointerInput(message) {
                                            detectTapGestures(
                                                onDoubleTap = { toggleHeart(message) }
                                            )
                                        }
                                        .semantics(mergeDescendants = true) {
                                            if (message.hearted) stateDescription = "Hearted"
                                            customActions =
                                                listOf(
                                                    CustomAccessibilityAction(
                                                        if (message.hearted) "Remove heart"
                                                        else "React with heart"
                                                    ) {
                                                        toggleHeart(message)
                                                        true
                                                    }
                                                )
                                        },
                                    horizontalAlignment =
                                        if (message.outgoing) Alignment.Start else Alignment.End,
                                ) {
                                    val bubbleModifier = Modifier.clip(Theme.shapes.large)
                                    when (val content = message.content) {
                                        is MessageContent.Text -> {
                                            Box(
                                                bubbleModifier
                                                    .widthIn(max = 320.dp)
                                                    .then(
                                                        if (message.outgoing) Modifier
                                                        else
                                                            Modifier.border(
                                                                1.dp,
                                                                Theme.colors.border,
                                                                Theme.shapes.large,
                                                            )
                                                    )
                                                    .background(
                                                        if (message.outgoing) Theme.colors.accent
                                                        else Theme.colors.background
                                                    )
                                                    .padding(horizontal = 16.dp, vertical = 12.dp)
                                            ) {
                                                Text(
                                                    content.value,
                                                    color =
                                                        if (message.outgoing) Theme.colors.onAccent
                                                        else Theme.colors.onBackground,
                                                    style = Theme.typography.body,
                                                )
                                            }
                                        }
                                        is MessageContent.Gif -> {
                                            Image(
                                                painter =
                                                    rememberUriPainter(
                                                        content.imageUrl,
                                                        crossfade = 300.milliseconds,
                                                        contentScale = ContentScale.Crop,
                                                    ),
                                                contentDescription = content.description,
                                                contentScale = ContentScale.Crop,
                                                modifier =
                                                    bubbleModifier.size(
                                                        width = 200.dp,
                                                        height = 150.dp,
                                                    ),
                                            )
                                        }
                                    }
                                    AnimatedVisibility(
                                        visible = message.hearted,
                                        modifier =
                                            Modifier.padding(horizontal = 12.dp).layout {
                                                measurable,
                                                constraints ->
                                                // Overlaps the bubble's bottom edge.
                                                val overlap = 10.dp.roundToPx()
                                                val placeable = measurable.measure(constraints)
                                                layout(
                                                    placeable.width,
                                                    (placeable.height - overlap).coerceAtLeast(0),
                                                ) {
                                                    placeable.place(0, -overlap)
                                                }
                                            },
                                        enter = expandVertically() + scaleIn() + fadeIn(),
                                        exit = shrinkVertically() + scaleOut() + fadeOut(),
                                    ) {
                                        HeartBadge()
                                    }
                                }
                            }
                        }
                    }
                }

                ReplyBar(
                    modifier = Modifier.fillMaxWidth(),
                    value = draft,
                    gifs = conversationGifs,
                    onValueChange = { draft = it },
                    onSend = {
                        val text = draft.trim()
                        if (text.isNotEmpty()) {
                            send(MessageContent.Text(text))
                            draft = ""
                        }
                    },
                    onGifSelected = { gif ->
                        send(MessageContent.Gif(gif.description, gif.imageUrl))
                    },
                )
            }

            AlertDialog(
                visible = confirmingUnmatch,
                title = "Unmatch ${person.name}?",
                onDismissRequest = { confirmingUnmatch = false },
                body = {
                    Text(
                        "You will not be able to chat with this person anymore or match with them again."
                    )
                },
                positiveAction = {
                    Button(
                        onClick = {
                            confirmingUnmatch = false
                            unmatch()
                        },
                        modifier = Modifier.fillMaxWidth(),
                    ) {
                        Text("Yes, unmatch")
                    }
                },
                negativeAction = {
                    ChoiceButton(
                        selected = false,
                        onClick = { confirmingUnmatch = false },
                        modifier = Modifier.fillMaxWidth(),
                    ) {
                        Text("Cancel")
                    }
                },
            )

            ModalBottomSheet(
                visible = showOptions,
                onDismiss = { showOptions = false },
            ) {
                Text(
                    "Unmatch",
                    modifier =
                        Modifier.fillMaxWidth()
                            .clip(Theme.shapes.small)
                            .clickable(
                                interactionSource = remember { MutableInteractionSource() },
                                indication =
                                    rememberRippleIndication(color = Theme.colors.onBackground),
                            ) {
                                showOptions = false
                                confirmingUnmatch = true
                            }
                            .padding(16.dp),
                )
                Text(
                    "Report",
                    modifier =
                        Modifier.fillMaxWidth()
                            .clip(Theme.shapes.small)
                            .clickable(
                                interactionSource = remember { MutableInteractionSource() },
                                indication =
                                    rememberRippleIndication(color = Theme.colors.onBackground),
                            ) {
                                showOptions = false
                                reportPerson()
                            }
                            .padding(16.dp),
                )
                Text(
                    "Block",
                    modifier =
                        Modifier.fillMaxWidth()
                            .clip(Theme.shapes.small)
                            .clickable(
                                interactionSource = remember { MutableInteractionSource() },
                                indication =
                                    rememberRippleIndication(color = Theme.colors.destructive),
                            ) {
                                showOptions = false
                                blockPerson()
                            }
                            .padding(16.dp),
                    color = Theme.colors.destructive,
                )
            }
        }
    }
}

@Composable
private fun HeartBadge() {
    Box(
        Modifier.size(24.dp)
            .border(2.dp, Theme.colors.surface, CircleShape)
            .padding(2.dp)
            .clip(CircleShape)
            .background(Theme.colors.primary),
        contentAlignment = Alignment.Center,
    ) {
        Icon(
            Icons.Heart,
            contentDescription = null,
            modifier = Modifier.size(12.dp),
            tint = Theme.colors.background,
        )
    }
}

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.