@@ -28,16 +28,20 @@ import androidx.paging.compose.itemKey
2828import com.getcode.model.ID
2929import com.getcode.model.chat.MessageContent
3030import com.getcode.model.chat.MessageStatus
31+ import com.getcode.model.uuid
3132import com.getcode.theme.CodeTheme
3233import com.getcode.ui.components.chat.messagecontents.MessageControlAction
3334import com.getcode.ui.components.chat.utils.ChatItem
3435import com.getcode.ui.components.chat.utils.MessageTip
3536import com.getcode.ui.components.text.markup.Markup
3637import com.getcode.util.formatDateRelatively
38+ import com.getcode.utils.timestamp
3739import kotlinx.coroutines.flow.combine
3840import kotlinx.coroutines.flow.distinctUntilChanged
3941import kotlinx.coroutines.flow.filter
4042import kotlinx.coroutines.flow.filterNot
43+ import kotlinx.coroutines.flow.launchIn
44+ import kotlinx.coroutines.flow.onEach
4145
4246sealed interface MessageListEvent {
4347 data class AdvancePointer (val messageId : ID ) : MessageListEvent
@@ -275,12 +279,18 @@ private fun HandleMessageReads(
275279 }.distinctUntilChanged(),
276280 snapshotFlow { listState.isScrollInProgress },
277281 snapshotFlow { listState.firstVisibleItemIndex },
278- ) { loadState, isScrolling, firstVisibleIndex ->
279- Triple (loadState, isScrolling, firstVisibleIndex)
280- }.filter { (loadStateIsNotLoading, isScrolling, _) ->
281- // Wait until scrolling stops, messages are not loading, and we are at the bottom
282- loadStateIsNotLoading && ! isScrolling && messages.itemCount > 0 && hasSetAtUnread
283- }.collect { (_, _, firstVisibleIndex) ->
282+ snapshotFlow { messages.itemCount },
283+ ) { loadState, isScrolling, firstVisibleIndex, itemCount ->
284+ Triple (loadState, isScrolling, firstVisibleIndex) to itemCount
285+ }.filter { (state, itemCount) ->
286+ val (loadStateIsNotLoading, isScrolling, firstVisibleIndex) = state
287+ // Ensure we react to new messages while at the bottom
288+ loadStateIsNotLoading && ! isScrolling && hasSetAtUnread &&
289+ (firstVisibleIndex == 0 || firstVisibleIndex == itemCount - 1 ) && itemCount > 0
290+ }.onEach { (state, _) ->
291+
292+ val (_, _, firstVisibleIndex) = state
293+
284294 val closestChatMessage =
285295 messages[firstVisibleIndex]?.let { it as ? ChatItem .Message }
286296
@@ -298,7 +308,7 @@ private fun HandleMessageReads(
298308 }
299309 }
300310 }
301- }
311+ }.launchIn( this )
302312 }
303313}
304314
0 commit comments