From b6db6d040b4da5bf1ea60607699dd21c135dc115 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:14:48 +0200 Subject: [PATCH] feat: a room on screen is read, and what is not is counted (notifications, Phase 4) Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 3 + .../compose/database/dao/NotificationDao.kt | 13 ++- .../repository/DatabaseChatRepository.kt | 13 +++ .../giza/compose/notifications/UnreadBadge.kt | 35 ++++++ .../notifications/VisibleConversation.kt | 65 +++++++++++ .../giza/compose/repository/ChatRepository.kt | 13 +++ .../ui/composable/ChatRoomMessagingScreen.kt | 9 ++ .../ui/composable/navigation/GizaNavHost.kt | 12 ++ .../navigation/GizaNavigationSuite.kt | 42 +++++-- .../ui/view/model/ChatRoomListViewModel.kt | 37 ++++-- .../ui/view/state/ChatRoomListUIState.kt | 5 +- .../database/NotificationStorageJvmTest.kt | 2 +- .../managers/NotificationTodayJvmTest.kt | 10 +- .../compose/notifications/ReadStateJvmTest.kt | 106 ++++++++++++++++++ 14 files changed, 333 insertions(+), 32 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/UnreadBadge.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/ReadStateJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 0889e9ce..09abbd31 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -794,4 +794,7 @@ Send again Sent again The group's admins have changed since this key was made. It changes on its own once an admin's device starts a new ceremony, or you can rotate it now. + + Unread: %1$d + Conversations with unread messages: %1$d diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt index 089a71fd..cc707fe9 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NotificationDao.kt @@ -56,7 +56,8 @@ abstract class NotificationDao { /** Unread lines per room, for every room [userPublicKey] is in and has not left or deleted. */ @Query( - "SELECT ChatMessage.chatRoomId AS chatRoomId, COUNT(*) AS unread FROM ChatMessage " + + "SELECT ChatMessage.chatRoomId AS chatRoomId, COUNT(*) AS unread, " + + "ChatRoom.notifications AS notifications FROM ChatMessage " + "JOIN ChatRoom ON ChatRoom.id = ChatMessage.chatRoomId " + "WHERE ChatRoom.userPublicKey = :userPublicKey AND ChatRoom.deletedAt IS NULL " + "AND ChatRoom.leftGroupAt IS NULL AND ChatMessage.isUserMessage = 0 " + @@ -150,5 +151,11 @@ abstract class NotificationDao { } } -/** One room's unread count. */ -data class RoomUnread(val chatRoomId: String, val unread: Int) +/** One room's unread count, and whether the room is muted -- a muted room counts, quietly. */ +data class RoomUnread( + val chatRoomId: String, + val unread: Int, + val notifications: String, +) { + val isMuted: Boolean get() = notifications == mobi.giza.compose.database.model.ChatRoom.NOTIFICATIONS_MUTED +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 23f5ffc2..5977ba25 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -44,6 +44,7 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.map import mobi.giza.compose.database.GENESIS_AT import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.ChatMessage @@ -187,6 +188,18 @@ class DatabaseChatRepository( return database.chatRoomDao().observeChatRoomListByUserPublicKey(publicKey) } + override suspend fun markChatRoomRead(chatRoomId: String) { + database.notificationDao().markAllRead(chatRoomId) + } + + override fun observeUnreadCounts(publicKey: String): Flow> = + database.notificationDao().observeUnreadCounts(publicKey) + .map { counts -> counts.associateBy { it.chatRoomId } } + + override suspend fun setChatRoomNotifications(chatRoomId: String, notifications: String) { + database.notificationDao().setNotifications(chatRoomId, notifications) + } + override suspend fun getChatRoomListByPublicKey(publicKey: String): List { return database.chatRoomDao().getChatRoomListByUserPublicKey(publicKey) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/UnreadBadge.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/UnreadBadge.kt new file mode 100644 index 00000000..6a1d5955 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/UnreadBadge.kt @@ -0,0 +1,35 @@ +package mobi.giza.compose.notifications + +import androidx.compose.material3.Badge +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.unread_count +import org.jetbrains.compose.resources.stringResource + +/** + * A room's unread count, as an M3 large badge. A muted room's is drawn in the quieter secondary + * pair: still counted, not asking for attention. Read aloud as a sentence rather than a bare number, + * which beside a timestamp means nothing. docs/notifications-and-background-sync.md, Phase 4. + */ +@Composable +fun UnreadBadge(count: Int, muted: Boolean, modifier: Modifier = Modifier) { + if (count <= 0) return + val description = stringResource(Res.string.unread_count, count) + Badge( + modifier = modifier.clearAndSetSemantics { contentDescription = description }, + containerColor = if (muted) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.error, + contentColor = if (muted) MaterialTheme.colorScheme.onSecondaryContainer else MaterialTheme.colorScheme.onError, + ) { + Text(badgeText(count)) + } +} + +/** What fits in a badge: the count, or 999+ past it. */ +internal fun badgeText(count: Int): String = if (count > MAX_SHOWN) "$MAX_SHOWN+" else count.toString() + +private const val MAX_SHOWN = 999 diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt new file mode 100644 index 00000000..643f368d --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/VisibleConversation.kt @@ -0,0 +1,65 @@ +package mobi.giza.compose.notifications + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import mobi.giza.compose.AppLifecycle +import mobi.giza.compose.repository.ChatRepository + +/** + * The room whose transcript is on screen, or null. Read by the notification policy, which posts + * nothing for the room somebody is already looking at, and set by [MarkReadWhileVisible]. + * docs/notifications-and-background-sync.md, D7 and D8. + * + * A singleton for the reason `AppLifecycle` is one: its reader is an application-scoped coroutine + * that outlives every screen. + */ +object VisibleConversation { + private val _chatRoomId = MutableStateFlow(null) + + val chatRoomId: StateFlow = _chatRoomId.asStateFlow() + + fun entered(chatRoomId: String) { + _chatRoomId.value = chatRoomId + } + + /** Clears [chatRoomId] -- and only it: in a transition the next room may already have entered. */ + fun left(chatRoomId: String) { + _chatRoomId.update { current -> if (current == chatRoomId) null else current } + } +} + +/** + * Keeps [chatRoomId] read for as long as it is composed and the app is in front: once on entry, and + * again each time a line arrives in it. Also tells [VisibleConversation] which room is up. + * + * Emits no layout, so it can sit above a screen's `ScreenStateTransition` without taking that + * transition's branches out of their scope. + */ +@Composable +fun MarkReadWhileVisible( + activeUserPublicKey: String, + chatRoomId: String, + chatRepository: ChatRepository, +) { + val inFront by AppLifecycle.isForeground.collectAsState() + + DisposableEffect(chatRoomId) { + VisibleConversation.entered(chatRoomId) + onDispose { VisibleConversation.left(chatRoomId) } + } + + LaunchedEffect(activeUserPublicKey, chatRoomId, inFront) { + if (!inFront) return@LaunchedEffect + chatRepository.markChatRoomRead(chatRoomId) + chatRepository.observeUnreadCounts(activeUserPublicKey).collect { unread -> + if ((unread[chatRoomId]?.unread ?: 0) > 0) chatRepository.markChatRoomRead(chatRoomId) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index acd623f8..42bfb909 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -34,6 +34,19 @@ import mobi.giza.compose.ui.view.state.RotationPreview interface ChatRepository { suspend fun observeChatRoomListByPublicKey(publicKey: String): Flow> + /** + * Marks [chatRoomId] read up to its newest line. A no-op where nothing stores read state. + * docs/notifications-and-background-sync.md, D8. + */ + suspend fun markChatRoomRead(chatRoomId: String) {} + + /** Each of [publicKey]'s rooms that has unread lines, by room id. Empty where nothing stores them. */ + fun observeUnreadCounts(publicKey: String): Flow> = + kotlinx.coroutines.flow.flowOf(emptyMap()) + + /** Mutes or unmutes [chatRoomId]: [mobi.giza.compose.database.model.ChatRoom.NOTIFICATIONS_ALL] or `…_MUTED`. */ + suspend fun setChatRoomNotifications(chatRoomId: String, notifications: String) {} + suspend fun getChatRoomListByPublicKey(publicKey: String): List suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom? diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt index 39b9166a..58cb2cba 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt @@ -33,6 +33,7 @@ import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import mobi.giza.compose.notifications.MarkReadWhileVisible import androidx.compose.runtime.key import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -108,6 +109,14 @@ fun ChatRoomMessagingScreen( ) ) + // Read while it is on screen, and the room the notification policy stays quiet about. + // docs/notifications-and-background-sync.md, Phase 4. + MarkReadWhileVisible( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + chatRepository = chatRepository, + ) + ScreenStateTransition(chatRoomMessagingViewModel.chatRoomMessagingUIState) { uiState -> when (val chatRoomDetailUIState = uiState) { is ChatRoomMessagingUIState.Error -> { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index 5aa40afc..39cc3e56 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -160,6 +160,8 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute import mobi.giza.compose.ui.composable.navigation.routes.ProposalListRoute @@ -388,12 +390,22 @@ fun GizaNavHost( // Once, above every screen: what a read-only identity may not be offered is decided // where the control is drawn, and this is how the control finds out. + // The rooms with something unread, muted ones left out: a muted room counts on its own row + // and stays off the tab. docs/notifications-and-background-sync.md, Phase 4. + val unreadConversations by remember(activeUserPublicKey) { + activeUserPublicKey + ?.let { publicKey -> databaseChatRepository.observeUnreadCounts(publicKey) } + ?.map { unread -> unread.values.count { !it.isMuted } } + ?: flowOf(0) + }.collectAsState(0) + ProvideSigningCapability(sovereignWalletViewModel.activeIdentity) { GizaNavigationSuite( navController = navController, breakpoint = MaterialTheme.breakpoint, activeUserPublicKey = activeUserPublicKey, activeProfileNostrEventId = activeProfileNostrEventId, + unreadConversations = unreadConversations, ) { NavHost( navController = navController, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavigationSuite.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavigationSuite.kt index f8ba46c1..924eb05e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavigationSuite.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavigationSuite.kt @@ -1,5 +1,12 @@ package mobi.giza.compose.ui.composable.navigation +import androidx.compose.material3.Badge +import androidx.compose.material3.BadgedBox +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.unread_conversations import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon import androidx.compose.material3.Text @@ -57,6 +64,11 @@ fun GizaNavigationSuite( breakpoint: Breakpoint, activeUserPublicKey: String?, activeProfileNostrEventId: String?, + /** + * Conversations with unread messages, shown on [TopLevelDestination.Messages]. Muted rooms are + * left out by the caller. docs/notifications-and-background-sync.md, Phase 4. + */ + unreadConversations: Int = 0, content: @Composable () -> Unit, ) { val currentDestination: NavDestination? = @@ -116,14 +128,28 @@ fun GizaNavigationSuite( } }, icon = { - Icon( - imageVector = destination.icon, - // The label is beside the icon in the bar and in the expanded - // rail, and a reader would hear the name twice. The collapsed - // rail is the exception, and it draws the label as a tooltip - // the accessibility tree still carries. - contentDescription = Decorative, - ) + val icon = @Composable { + Icon( + imageVector = destination.icon, + // The label is beside the icon in the bar and in the expanded + // rail, and a reader would hear the name twice. The collapsed + // rail is the exception, and it draws the label as a tooltip + // the accessibility tree still carries. + contentDescription = Decorative, + ) + } + if (destination == TopLevelDestination.Messages && unreadConversations > 0) { + val description = stringResource(Res.string.unread_conversations, unreadConversations) + BadgedBox( + badge = { + Badge(modifier = Modifier.clearAndSetSemantics { contentDescription = description }) { + Text(unreadConversations.toString()) + } + }, + ) { icon() } + } else { + icon() + } }, label = { Text(stringResource(destination.label)) }, ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomListViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomListViewModel.kt index 75d070ff..c8ca2eb0 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomListViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomListViewModel.kt @@ -40,6 +40,8 @@ import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.launch +import kotlinx.coroutines.flow.combine +import mobi.giza.compose.notifications.UnreadBadge import mobi.giza.compose.ui.theme.spacing import mobi.giza.compose.resources.Res import org.jetbrains.compose.resources.stringResource @@ -68,11 +70,11 @@ class ChatRoomListViewModel( viewModelScope.launch(Dispatchers.IO) { chatRepository.observeChatRoomListByPublicKey( publicKey - ).collect { chatRooms -> - logger.d("ChatRoomList: $chatRooms") - chatRoomListUIState = ChatRoomListUIState.Loaded( - chatRoomList = chatRooms - ) + ).combine(chatRepository.observeUnreadCounts(publicKey)) { chatRooms, unread -> + ChatRoomListUIState.Loaded(chatRoomList = chatRooms, unread = unread) + }.collect { loaded -> + logger.d("ChatRoomList: ${loaded.chatRoomList.size} room(s), ${loaded.unread.size} unread") + chatRoomListUIState = loaded } } } @@ -210,13 +212,24 @@ class ChatRoomListViewModel( // and the room's own creation -- which is // what it sorts on -- is not one the user // has any reason to read here. - localChatRoom.lastChatMessage?.let { lastChatMessage -> - Text( - text = lastChatMessage.createdAt.toChatListTimestampString(), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1 - ) + Column( + horizontalAlignment = Alignment.End, + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) + ) { + localChatRoom.lastChatMessage?.let { lastChatMessage -> + Text( + text = lastChatMessage.createdAt.toChatListTimestampString(), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1 + ) + } + + // What has not been read, said beside the time + // it was said. docs/notifications-and-background-sync.md, Phase 4. + chatRoomListUIState.unread[localChatRoom.chatRoom.id]?.let { roomUnread -> + UnreadBadge(count = roomUnread.unread, muted = roomUnread.isMuted) + } } } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomListUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomListUIState.kt index 91844e41..0b12d300 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomListUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomListUIState.kt @@ -2,10 +2,11 @@ package mobi.giza.compose.ui.view.state sealed interface ChatRoomListUIState { data class Loaded( - val chatRoomList: List + val chatRoomList: List, + /** Rooms with unread lines, by room id. A room absent here has none. */ + val unread: Map = emptyMap(), ): ChatRoomListUIState data object Error: ChatRoomListUIState data object Loading: ChatRoomListUIState } - diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/NotificationStorageJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/NotificationStorageJvmTest.kt index 495ceaf5..df6759b5 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/NotificationStorageJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/NotificationStorageJvmTest.kt @@ -88,7 +88,7 @@ class NotificationStorageJvmTest { line() assertEquals(1, dao.unreadCount(roomOne)) - assertEquals(listOf(mobi.giza.compose.database.dao.RoomUnread(roomOne, 1)), dao.observeUnreadCounts(user).first()) + assertEquals(listOf(mobi.giza.compose.database.dao.RoomUnread(roomOne, 1, ChatRoom.NOTIFICATIONS_ALL)), dao.observeUnreadCounts(user).first()) } @Test diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt index a4d10894..21af8854 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/NotificationTodayJvmTest.kt @@ -9,7 +9,6 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull -import kotlin.test.assertNull import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking @@ -38,11 +37,11 @@ class NotificationTodayJvmTest { /** * The premise of the background pass (Phase 0, check 5): a Welcome and the first message after - * it are filed by `storeNostrEvent` alone, with no view model running. And nothing records that - * the message has not been read -- the room carries no read state at all. + * it are filed by `storeNostrEvent` alone, with no view model running. Phase 4 flipped the second + * half: the room now knows the message has not been read. */ @Test - fun `a group message is filed with no view model, and nothing marks it unread`() = runBlocking { + fun `a group message is filed with no view model, and counts as unread`() = runBlocking { MarmotStandIn.seedProfile(db, userHex, "us") MarmotStandIn.seedProfile(db, peer.hex, "peer") val roomId = peer.inviteApp(db, marmotRepository, user, peer.createGroup("notify")) @@ -58,8 +57,7 @@ class NotificationTodayJvmTest { ) assertFalse(line.isUserMessage) - // Phase 4 flips this: the room will say how far it has been read. - assertNull(assertNotNull(db.chatRoomDao().findChatRoomById(roomId)).chatRoom.viewedAt) + assertEquals(1, db.notificationDao().unreadCount(roomId)) } private val source: File = diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/ReadStateJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/ReadStateJvmTest.kt new file mode 100644 index 00000000..69c41e06 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/ReadStateJvmTest.kt @@ -0,0 +1,106 @@ +package mobi.giza.compose.notifications + +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.runDesktopComposeUiTest +import androidx.room3.Room +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.time.Instant +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.repository.DatabaseChatRepository + +/** + * A room on screen stays read; one that is not counts what arrives in it. + * docs/notifications-and-background-sync.md, Phase 4. + */ +class ReadStateJvmTest { + + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + private val chatRepository = DatabaseChatRepository(db, CoroutineScope(Dispatchers.Default)) + + @AfterTest + fun closeDb() = db.close() + + private val user = "a".repeat(64) + private val peer = "b".repeat(64) + private val open = "11".repeat(32) + private val elsewhere = "22".repeat(32) + + private fun seed() = runBlocking { + listOf(user, peer).forEach { publicKey -> + val eventId = publicKey.take(32).padEnd(64, 'c') + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = publicKey, userName = publicKey.take(4), nostrEventId = eventId)) + } + listOf(open, elsewhere).forEach { id -> + db.chatRoomDao().upsert(ChatRoom(id = id, userPublicKey = user, subject = null, description = null, mlsGroupState = null)) + } + } + + private fun line(room: String, mine: Boolean = false) = runBlocking { + db.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = if (mine) user else peer, + isUserMessage = mine, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = room, + content = "hello", + createdAt = Instant.fromEpochSeconds(1_800_000_000), + ) + ) + } + + private fun unread(room: String) = runBlocking { db.notificationDao().unreadCount(room) } + + @OptIn(ExperimentalTestApi::class) + @Test + fun `the room on screen is read on entry and as lines arrive, and the one off screen counts`() { + seed() + line(open) + line(open) + + runDesktopComposeUiTest { + setContent { MarkReadWhileVisible(activeUserPublicKey = user, chatRoomId = open, chatRepository = chatRepository) } + + waitUntil(timeoutMillis = 5_000) { unread(open) == 0 } + assertEquals(open, VisibleConversation.chatRoomId.value) + + line(open) + line(elsewhere) + waitUntil(timeoutMillis = 5_000) { unread(open) == 0 } + assertEquals(1, unread(elsewhere)) + } + + // Out of the composition, it is no longer the room on screen. + assertNull(VisibleConversation.chatRoomId.value) + } + + @Test + fun `a room left is cleared only if it is still the one recorded`() { + VisibleConversation.entered(open) + VisibleConversation.entered(elsewhere) + VisibleConversation.left(open) + assertEquals(elsewhere, VisibleConversation.chatRoomId.value, "leaving the old room cleared the new one") + VisibleConversation.left(elsewhere) + assertNull(VisibleConversation.chatRoomId.value) + } + + @Test + fun `a badge says the count, and stops at 999`() { + assertEquals("7", badgeText(7)) + assertEquals("999", badgeText(999)) + assertEquals("999+", badgeText(1_000)) + } +}