Scroll to the bottom on sending a message

This commit is contained in:
Lonami Exo 2022-10-11 21:34:18 +02:00
parent 29c164c4ae
commit 57cc2119dd
1 changed files with 15 additions and 3 deletions

View File

@ -2,6 +2,8 @@ package dev.lonami.talaria.ui
import androidx.compose.foundation.layout.* import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Button import androidx.compose.material.Button
@ -19,6 +21,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel
import dev.lonami.talaria.R import dev.lonami.talaria.R
import dev.lonami.talaria.model.Message import dev.lonami.talaria.model.Message
import dev.lonami.talaria.ui.theme.TalariaTheme import dev.lonami.talaria.ui.theme.TalariaTheme
import kotlinx.coroutines.launch
@Composable @Composable
fun MessageCard(message: Message) { fun MessageCard(message: Message) {
@ -40,8 +43,8 @@ fun MessageCard(message: Message) {
} }
@Composable @Composable
fun MessageList(messages: List<Message>, modifier: Modifier) { fun MessageList(messages: List<Message>, modifier: Modifier, listState: LazyListState) {
LazyColumn(modifier) { LazyColumn(modifier, state = listState) {
items(messages.size) { MessageCard(messages[it]) } items(messages.size) { MessageCard(messages[it]) }
} }
} }
@ -77,14 +80,23 @@ fun MessageInputField(
fun ChatScreen(chatViewModel: ChatViewModel = viewModel()) { fun ChatScreen(chatViewModel: ChatViewModel = viewModel()) {
val chatUiState by chatViewModel.uiState.collectAsState() val chatUiState by chatViewModel.uiState.collectAsState()
var messageText by remember { mutableStateOf("") } var messageText by remember { mutableStateOf("") }
val messageListState = rememberLazyListState()
val coroutineScope = rememberCoroutineScope()
Column(modifier = Modifier.fillMaxSize()) { Column(modifier = Modifier.fillMaxSize()) {
MessageList(chatUiState.messages, modifier = Modifier.weight(1.0f)) MessageList(
chatUiState.messages,
modifier = Modifier.weight(1.0f),
listState = messageListState
)
MessageInputField(messageText, onMessageChanged = { MessageInputField(messageText, onMessageChanged = {
messageText = it messageText = it
}, onSendMessage = { }, onSendMessage = {
chatViewModel.sendMessage(messageText) chatViewModel.sendMessage(messageText)
messageText = "" messageText = ""
coroutineScope.launch {
messageListState.animateScrollToItem(chatUiState.messages.size - 1)
}
}) })
} }
} }