feat: a room on screen is read, and what is not is counted (notifications, Phase 4)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-22 12:14:48 +02:00
1 parent c248ab529c
commit b6db6d040b
14 files changed
+333 -32

No files matched your search

@@ -794,4 +794,7 @@
<string name="send_reply_again">Send again</string>
<string name="sent_again">Sent again</string>
<string name="the_admins_have_changed_since_this_key_was_made">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.</string>
<!-- Notifications and read state (docs/notifications-and-background-sync.md) -->
<string name="unread_count">Unread: %1$d</string>
<string name="unread_conversations">Conversations with unread messages: %1$d</string>
</resources>
@@ -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
}
@@ -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<Map<String, mobi.giza.compose.database.dao.RoomUnread>> =
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<LocalChatRoom> {
return database.chatRoomDao().getChatRoomListByUserPublicKey(publicKey)
}
@@ -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
@@ -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<String?>(null)
val chatRoomId: StateFlow<String?> = _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)
}
}
}
@@ -34,6 +34,19 @@ import mobi.giza.compose.ui.view.state.RotationPreview
interface ChatRepository {
suspend fun observeChatRoomListByPublicKey(publicKey: String): Flow<List<LocalChatRoom>>
/**
* 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<Map<String, mobi.giza.compose.database.dao.RoomUnread>> =
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<LocalChatRoom>
suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom?
@@ -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 -> {
@@ -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,
@@ -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)) },
)
@@ -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)
}
}
}
}
@@ -2,10 +2,11 @@ package mobi.giza.compose.ui.view.state
sealed interface ChatRoomListUIState {
data class Loaded(
val chatRoomList: List<mobi.giza.compose.database.model.intermdiate.LocalChatRoom>
val chatRoomList: List<mobi.giza.compose.database.model.intermdiate.LocalChatRoom>,
/** Rooms with unread lines, by room id. A room absent here has none. */
val unread: Map<String, mobi.giza.compose.database.dao.RoomUnread> = emptyMap(),
): ChatRoomListUIState
data object Error: ChatRoomListUIState
data object Loading: ChatRoomListUIState
}