diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 34495a8d..2ae879e0 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -613,4 +613,19 @@ What the group says about itself on Nostr Not described yet This device holds no profile for this group. A profile signed before you joined isn't passed on. + + Add post + A post needs something to say. + A reply + Couldn't ask the group to sign this post. + Posted %1$s + Posts + Propose post + The group signs a post, so it takes a quorum. It goes out in the group's name, not yours, and can't be taken back once signed. + This device holds no posts by this group. Posts signed before you joined aren't passed on. + This group has no shared key, so it cannot sign a post. Run a shared key ceremony first. + What should the group say? + No posts yet + 1 post + %1$d posts diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/AddGroupPostScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/AddGroupPostScreen.kt new file mode 100644 index 00000000..d6877905 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/AddGroupPostScreen.kt @@ -0,0 +1,313 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Draw +import androidx.compose.material3.BottomAppBar +import androidx.compose.material3.BottomAppBarDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.FrostSigningRepository +import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.ErrorState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.composable.widgets.buttons.ExtendedFab +import mobi.giza.compose.ui.composable.widgets.profile.ProfileAvatar +import mobi.giza.compose.ui.composable.widgets.rememberNotifier +import mobi.giza.compose.ui.theme.ConformancePreviews +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.AddGroupPostViewModel +import mobi.giza.compose.ui.view.state.AddGroupPostUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.a_post_needs_something_to_say +import mobi.giza.compose.resources.add_post +import mobi.giza.compose.resources.could_not_ask_the_group_to_sign_this_post +import mobi.giza.compose.resources.propose_post +import mobi.giza.compose.resources.the_group_signs_a_post_so_it_takes_a_quorum +import mobi.giza.compose.resources.this_group_has_no_shared_key_to_sign_a_post +import mobi.giza.compose.resources.what_should_the_group_say +import org.jetbrains.compose.resources.stringResource + +/** + * The draft of something the group would say, in its own name. + * + * Not a message in the room: this is signed by the group's key and read by anybody, + * which is why the byline over the draft is the group's rather than the writer's. + * Whoever types it is proposing words for the group to put its signature to, and + * the words become a post -- attributed to the group and to nobody in particular -- + * only once a quorum has signed. + * + * The byline is the whole of the design here. Every other composer in this app puts + * the author's name over the draft because the author is the person typing; getting + * that wrong on this screen would have a member writing what looks like their own + * note and finding the group had said it. + */ +@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) +@Composable +fun AddGroupPostScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + initialAddGroupPostUIState: AddGroupPostUIState = AddGroupPostUIState.Loading, + chatRepository: ChatRepository, + frostSigningRepository: FrostSigningRepository, + onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val addGroupPostViewModel: AddGroupPostViewModel = viewModel( + factory = AddGroupPostViewModel.factory( + chatRoomId = chatRoomId, + relayHint = relayHint, + initialAddGroupPostUIState = initialAddGroupPostUIState, + activeUserPublicKey = activeUserPublicKey, + chatRepository = chatRepository, + frostSigningRepository = frostSigningRepository + ) + ) + + // Read out here rather than in the click handler: both are composable and an + // onClick lambda is not. The scope is the caller's so a message survives this + // screen being replaced by the signing session. + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_this_post) + val nothingToSay = stringResource(Res.string.a_post_needs_something_to_say) + + ScreenStateTransition(addGroupPostViewModel.addGroupPostUIState) { uiState -> + when (val addGroupPostUIState = uiState) { + is AddGroupPostUIState.Error -> { + // Nothing to retry: the room came from a navigation argument, and + // reading it again with the same one fails the same way. + ErrorState(message = addGroupPostUIState.message, onRetry = null) + } + + is AddGroupPostUIState.Loaded -> { + val noteFieldState = rememberTextFieldState() + // The room and this device's share, and the identity: an npub-only + // profile cannot send the proposal at all. docs/npub-sign-in.md. + val canSign = addGroupPostUIState.canSign && LocalCanSign.current + + // imePadding: this screen is a text field the size of the screen, + // and without it the software keyboard covers what is being typed. + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + modifier = Modifier.imePadding(), + topBar = { + TopAppBar( + title = { Text(text = stringResource(Res.string.add_post)) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + bottomBar = { + BottomAppBar( + actions = {}, + floatingActionButton = { + ExtendedFab( + label = stringResource(Res.string.propose_post), + icon = { Icon(Icons.Default.Draw, contentDescription = "Propose post") }, + enabled = canSign, + onClick = { + addGroupPostViewModel.proposePost( + localChatRoom = addGroupPostUIState.localChatRoom, + noteField = noteFieldState, + onSuccess = { sessionId -> + // Onto the session rather than back + // to the group. Nothing has been + // posted yet -- the post appears + // when a quorum signs -- so landing + // on the list it is not in would + // read as a failure. + onNavigateToRouteAndPopUpInclusive.invoke( + FrostSigningRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + sessionId = sessionId + ) + ) + }, + // Both stay on the draft. One is an + // empty note and one is a failure to + // propose, and neither is a reason to + // throw away what was written. + onEmpty = { notify(nothingToSay) }, + onFailure = { notify(couldNotPropose) } + ) + } + ) + } + ) + } + ) { innerPadding -> + Column( + modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize(), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + horizontalAlignment = Alignment.CenterHorizontally + ) { + // Whose name this goes out in, said before a word is typed. + // It is the group's, and it is the one thing about this + // screen a member could reasonably get wrong. + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + ProfileAvatar( + size = MaterialTheme.spacing.space500, + publicKey = chatRoomId, + picture = addGroupPostUIState.groupNostrProfile?.picture(), + name = addGroupPostUIState.groupNostrProfile?.name() + ) + + Spacer(modifier = Modifier.width(MaterialTheme.spacing.itemGap)) + + Text( + text = addGroupPostUIState.groupNostrProfile?.name() + ?: addGroupPostUIState.localChatRoom.chatRoom.subject + ?: chatRoomId.take(16), + style = MaterialTheme.typography.titleSmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + + Text( + text = stringResource( + Res.string.the_group_signs_a_post_so_it_takes_a_quorum + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center + ) + + if (!addGroupPostUIState.canSign) { + Text( + text = stringResource( + Res.string.this_group_has_no_shared_key_to_sign_a_post + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + textAlign = TextAlign.Center + ) + } + + OutlinedTextField( + modifier = Modifier.fillMaxWidth().weight(1f) + .background(BottomAppBarDefaults.containerColor), + state = noteFieldState, + // The draft grows into the screen rather than scrolling + // inside three lines: a post is the one thing here + // somebody writes at length, and a composer that hides + // what was written two sentences ago is a composer + // nobody proofreads in. + lineLimits = TextFieldLineLimits.MultiLine(), + colors = OutlinedTextFieldDefaults.colors( + focusedBorderColor = Color.Transparent, + unfocusedBorderColor = Color.Transparent, + disabledBorderColor = Color.Transparent + ), + placeholder = { + Text(stringResource(Res.string.what_should_the_group_say)) + } + ) + } + } + } + + AddGroupPostUIState.Loading -> { + Column( + modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.screenMargin), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) + ) { + Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) + + Text( + text = stringResource(Res.string.add_post), + style = MaterialTheme.typography.bodyLarge, + textAlign = TextAlign.Center + ) + + LoadingDataIndicator(fillScreen = false) + } + } + } + } + + LaunchedEffect(true) { + if (initialAddGroupPostUIState == AddGroupPostUIState.Loading) { + addGroupPostViewModel.initiateAddGroupPost() + } + } +} + +@ConformancePreviews +@Composable +private fun AddGroupPostScreenPreview() { + GizaTheme { + Surface(modifier = Modifier.fillMaxSize()) { + AddGroupPostScreen( + activeUserPublicKey = "", + chatRoomId = "publicKey", + relayHint = null, + initialAddGroupPostUIState = AddGroupPostUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom( + id = "publicKey", + userPublicKey = "", + subject = "Translation room", + description = "A group translating hard books.", + initialGiftWrapPayloadId = "sdfaer", + mlsGroupState = "state" + ), + ), + // A group that can sign, so the composer renders in the state a + // member actually meets it in rather than greyed out. + canSign = true + ), + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, + onNavigateToRouteAndPopUpInclusive = {}, + onNavigateBack = {}, + ) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 2f1cead8..fee5952e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -1,5 +1,11 @@ package mobi.giza.compose.ui.composable +import mobi.giza.compose.resources.n_posts +import mobi.giza.compose.resources.one_post +import mobi.giza.compose.resources.no_posts_yet +import mobi.giza.compose.resources.posts +import mobi.giza.compose.ui.composable.navigation.routes.GroupPostsRoute +import androidx.compose.material.icons.filled.Campaign import mobi.giza.compose.resources.not_described_yet import mobi.giza.compose.resources.no_name_on_this_profile import mobi.giza.compose.resources.nostr_profile @@ -651,8 +657,9 @@ fun ChatRoomDetailScreen( HorizontalDivider() } - // What the group says about itself on nostr, as the group - // signed it (docs/group-nostr-profile-and-posts.md). A + // What the group says about itself on nostr and what it has + // posted, as the group signed them + // (docs/group-nostr-profile-and-posts.md). A // Marmot room only: the room's id is the key it signs as, // and a NIP-17 room has no key of its own to describe. // Shown to every member -- the profile is worth reading @@ -674,6 +681,22 @@ fun ChatRoomDetailScreen( ) } + // What the group has said publicly, as itself. + item { + GroupPostsRow( + postCount = chatRoomDetailUIState.groupPosts.size, + onClick = { + onNavigateToRoute.invoke( + GroupPostsRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = relayHint + ) + ) + } + ) + } + item { HorizontalDivider() } @@ -2004,3 +2027,40 @@ private fun GroupNostrProfileRow( ) } } + +/** + * The row on the group's screen that leads to its posts, counting them. A count + * rather than the newest post: the posts screen is where they are read whole, and + * a quote here would be the words twice with the second copy cut short. + */ +@Composable +private fun GroupPostsRow( + postCount: Int, + onClick: () -> Unit, +) { + Card( + modifier = Modifier.fillMaxWidth(), + onClick = onClick + ) { + ListItem( + leadingContent = { + Icon(Icons.Default.Campaign, contentDescription = Decorative) + }, + trailingContent = { + Icon(Icons.Default.ChevronRight, contentDescription = Decorative) + }, + headlineContent = { + Text(text = stringResource(Res.string.posts)) + }, + supportingContent = { + Text( + text = when (postCount) { + 0 -> stringResource(Res.string.no_posts_yet) + 1 -> stringResource(Res.string.one_post) + else -> stringResource(Res.string.n_posts, postCount) + } + ) + } + ) + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupPostsScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupPostsScreen.kt new file mode 100644 index 00000000..c95d8b62 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupPostsScreen.kt @@ -0,0 +1,334 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Campaign +import androidx.compose.material3.Card +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.a_reply +import mobi.giza.compose.resources.add_post +import mobi.giza.compose.resources.posted_on +import mobi.giza.compose.resources.posts +import mobi.giza.compose.resources.this_device_holds_no_posts_for_this_group +import org.jetbrains.compose.resources.stringResource +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.GroupSignedEvent +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.extensions.inComparableGroups +import mobi.giza.compose.extensions.toFormattedTimeAndDateString +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.nostr.GroupPost +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.ui.composable.navigation.routes.AddGroupPostRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.composable.widgets.EmptyState +import mobi.giza.compose.ui.composable.widgets.ErrorState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.composable.widgets.profile.ProfileAvatar +import mobi.giza.compose.ui.theme.ConformancePreviews +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.GroupPostsViewModel +import mobi.giza.compose.ui.view.state.GroupPostsUIState +import kotlin.time.Instant + +/** + * What the group has said publicly, as itself, newest first. + * + * Pushed from its row on the group's screen, which counts the posts and nothing + * more. This is where they are read: one card per post and -- for a member + * holding a share of the key -- the way into the composer. A device holding no + * posts says so, and offers the composer from the same place; a post signed + * before this member joined is not passed on (docs/group-nostr-profile-and-posts.md, + * D8), so "holds none" is all it can say. + * + * A post is the one thing the group signs that is meant to be *read* by people + * who were never in the room, so a member without a share reads it like + * anybody else and simply cannot propose the next one: proposing is a signature + * by the group, and `proposeSigningBatch` throws for a device holding no share. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GroupPostsScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + initialGroupPostsUIState: GroupPostsUIState = GroupPostsUIState.Loading, + chatRepository: ChatRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val groupPostsViewModel: GroupPostsViewModel = viewModel( + factory = GroupPostsViewModel.factory( + chatRoomId = chatRoomId, + initialGroupPostsUIState = initialGroupPostsUIState, + chatRepository = chatRepository, + ) + ) + + LaunchedEffect(true) { + if (initialGroupPostsUIState == GroupPostsUIState.Loading) { + groupPostsViewModel.initiate() + } + } + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { + Text( + text = stringResource(Res.string.posts), + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + }, + navigationIcon = { NavigateBackButton(onNavigateBack) } + ) + } + ) { padding -> + ScreenStateTransition(groupPostsViewModel.groupPostsUIState) { uiState -> + when (val state = uiState) { + is GroupPostsUIState.Error -> { + // Nothing to retry: the room came from a navigation argument, + // and reading it again with the same one fails the same way. + ErrorState( + modifier = Modifier.padding(padding), + message = state.message, + onRetry = null + ) + } + + GroupPostsUIState.Loading -> { + Column( + modifier = Modifier.fillMaxWidth().padding(padding) + .padding(MaterialTheme.spacing.screenMargin), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) + ) { + Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) + + LoadingDataIndicator(fillScreen = false) + } + } + + is GroupPostsUIState.Loaded -> { + // The room and this device's share, and the identity: an + // npub-only profile cannot send a proposal at all. + val canPropose = state.canSign && LocalCanSign.current + val add: () -> Unit = { + onNavigateToRoute.invoke( + AddGroupPostRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = relayHint + ) + ) + } + + LazyColumn( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .padding(MaterialTheme.spacing.space250), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) + ) { + if (state.groupPosts.isEmpty()) { + item { + EmptyState( + message = stringResource( + Res.string.this_device_holds_no_posts_for_this_group + ), + action = if (canPropose) { + { AddPostButton(onClick = add) } + } else { + null + } + ) + } + } else { + items( + items = state.groupPosts, + key = { post -> post.signedEvent.id } + ) { post -> + GroupPostCard( + post = post, + publicKey = chatRoomId, + groupNostrProfile = state.groupNostrProfile + ) + } + + if (canPropose) { + item { + AddPostButton(onClick = add) + } + } + } + } + } + } + } + } +} + +/** + * One thing the group said, as the group signed it. + * + * The whole note rather than a preview. A post is short by construction -- kind:1 + * with no long-form arm behind it -- and truncating the one kind of content on this + * screen that exists to be *read* would mean opening something to see a paragraph. + * + * **The byline is the group's**, taken from its profile where it has one and from + * the room's own id where it has not. It is worth spelling out because a post is + * the one thing here a reader might otherwise attribute to whichever member + * proposed it -- and the point of signing it as the group is that they cannot. + * + * A reply is marked as one. Nothing in this app writes replies, so the mark is for + * an event that arrived some other way; drawing one as an announcement would put + * half a conversation on a group's page with no sign that it was half. + */ +@Composable +private fun GroupPostCard( + post: GroupPost, + publicKey: HexKey, + groupNostrProfile: GroupNostrProfile? +) { + Card(modifier = Modifier.fillMaxWidth()) { + Column( + modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + ProfileAvatar( + size = MaterialTheme.spacing.space400, + publicKey = publicKey, + picture = groupNostrProfile?.picture(), + name = groupNostrProfile?.name() + ) + + Spacer(modifier = Modifier.width(MaterialTheme.spacing.itemGap)) + + Column(modifier = Modifier.weight(1f)) { + Text( + text = groupNostrProfile?.name() ?: publicKey.take(16).inComparableGroups(), + style = MaterialTheme.typography.titleSmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + + Text( + text = stringResource( + Res.string.posted_on, + post.postedAt.toFormattedTimeAndDateString() + ), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + if (!post.isNewThread()) { + Text( + text = stringResource(Res.string.a_reply), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + Text( + text = post.content, + style = MaterialTheme.typography.bodyMedium + ) + } + } +} + +/** The way into `AddGroupPostScreen`. The icon is decorative because the label is beside it. */ +@Composable +private fun AddPostButton(onClick: () -> Unit) { + TextButton(onClick = onClick) { + Icon(Icons.Default.Campaign, contentDescription = Decorative) + + Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) + + Text(stringResource(Res.string.add_post)) + } +} + +@ConformancePreviews +@Composable +private fun GroupPostsScreenPreview() { + val chatRoomId = "d".repeat(64) + + GizaTheme { + Surface(modifier = Modifier.fillMaxSize()) { + GroupPostsScreen( + activeUserPublicKey = "a".repeat(64), + chatRoomId = chatRoomId, + relayHint = null, + initialGroupPostsUIState = GroupPostsUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom( + id = chatRoomId, + userPublicKey = "a".repeat(64), + subject = "Translation room", + description = null, + initialGiftWrapPayloadId = "sdfaer", + mlsGroupState = "state" + ) + ), + groupPosts = listOf( + GroupPost( + signedEvent = GroupSignedEvent( + id = "b".repeat(64), + chatRoomId = chatRoomId, + publicKey = chatRoomId, + kind = TextNoteEvent.KIND, + tags = emptyArray(), + content = "The first chapter is out. Read it, and tell us where it reads wrong.", + signature = "f".repeat(128), + createdAt = Instant.fromEpochSeconds(1_700_000_000) + ) + ) + ), + canSign = true + ), + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + onNavigateToRoute = {}, + onNavigateBack = {}, + ) + } + } +} 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 47a44286..80f1be18 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 @@ -1,5 +1,9 @@ package mobi.giza.compose.ui.composable.navigation +import mobi.giza.compose.ui.composable.navigation.routes.AddGroupPostRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupPostsRoute +import mobi.giza.compose.ui.composable.AddGroupPostScreen +import mobi.giza.compose.ui.composable.GroupPostsScreen import mobi.giza.compose.ui.composable.navigation.routes.EditGroupNostrProfileRoute import mobi.giza.compose.ui.composable.navigation.routes.GroupNostrProfileRoute import mobi.giza.compose.ui.composable.EditGroupNostrProfileScreen @@ -1268,6 +1272,46 @@ fun GizaNavHost( } ) } + // The group's posts: docs/group-nostr-profile-and-posts.md. + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + GroupPostsScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + relayHint = route.relayHint, + chatRepository = databaseChatRepository, + onNavigateToRoute = { actionRoute -> + navController.navigate(route = actionRoute) + }, + onNavigateBack = { + navController.popBackStack() + } + ) + } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + AddGroupPostScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + relayHint = route.relayHint, + chatRepository = databaseChatRepository, + frostSigningRepository = databaseFrostSigningRepository, + onNavigateToRouteAndPopUpInclusive = { signingRoute -> + // Replace the composer so back returns to the posts rather + // than to a draft whose proposal has already gone out. + navController.navigate(route = signingRoute) { + popUpTo { + inclusive = true + } + } + }, + onNavigateBack = { + navController.popBackStack() + } + ) + } composable { backStackEntry -> val route: ImplementationPendingRoute = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/AddGroupPostRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/AddGroupPostRoute.kt new file mode 100644 index 00000000..7f246398 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/AddGroupPostRoute.kt @@ -0,0 +1,11 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** The composer that proposes a post for the group's quorum to sign as itself. */ +@Serializable +data class AddGroupPostRoute( + val activeUserPublicKey: String, + val chatRoomId: String, // TODO: have this as a publicKey + val relayHint: String? +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupPostsRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupPostsRoute.kt new file mode 100644 index 00000000..8cd9d4b5 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupPostsRoute.kt @@ -0,0 +1,15 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** + * What the group has said publicly, as itself, newest first, with the way into + * the composer for a member holding a share of the key. + * docs/group-nostr-profile-and-posts.md. + */ +@Serializable +data class GroupPostsRoute( + val activeUserPublicKey: String, + val chatRoomId: String, // TODO: have this as a publicKey + val relayHint: String? +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/AddGroupPostViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/AddGroupPostViewModel.kt new file mode 100644 index 00000000..a696c125 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/AddGroupPostViewModel.kt @@ -0,0 +1,156 @@ +package mobi.giza.compose.ui.view.model + +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import co.touchlab.kermit.Logger +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.managers.GroupStatementRefusal +import mobi.giza.compose.nostr.GroupPost +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.FrostSigningRepository +import mobi.giza.compose.ui.view.state.AddGroupPostUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.launch + +/** + * Asks the group to say something publicly, in its own name. + * + * The post is not written here and does not exist yet. What goes out is a proposal + * to sign one, and the post appears -- on every member's device at once, authored by + * the room's own key rather than by whoever typed it -- when enough members have + * signed. That author is the room's id: signing runs at the path the room was + * derived at, so a post says which group made it simply by being signed. + * + * That is the difference from a message in the room. A message is a member speaking + * where the group can hear; this is the group speaking where anyone can, and it + * takes a quorum to say. + */ +class AddGroupPostViewModel( + val chatRoomId: String, + val activeUserPublicKey: HexKey, + val relayHint: String?, + initialAddGroupPostUIState: AddGroupPostUIState, + val chatRepository: ChatRepository, + val frostSigningRepository: FrostSigningRepository, +): ViewModel() { + + var addGroupPostUIState: AddGroupPostUIState by mutableStateOf(initialAddGroupPostUIState) + private set + + private val logger = Logger.withTag(TAG) + + val isActionPending: MutableState = mutableStateOf(false) + + fun initiateAddGroupPost() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) + + addGroupPostUIState = if (localChatRoom == null) { + AddGroupPostUIState.Error("Couldn't find the chat room") + } else { + AddGroupPostUIState.Loaded( + localChatRoom = localChatRoom, + groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), + // The same condition the group detail screen gates the entry + // point on. + canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && + frostSigningRepository.canSign(chatRoomId), + ) + } + } + } + + /** + * Opens a session over one kind:1 authored by the group. + * + * Refuses a blank draft rather than proposing it: a quorum signing an empty note + * would put a post on the record that renders as nothing and cannot be told from + * a broken one -- and kind:1 is not replaceable, so there is no un-saying it. + * `GroupPost.newestFirstAmong` drops blanks on the way back out too, which is + * the second line of the same defence. + * + * The draft is not cleared on success. This screen is replaced by the signing + * session, and on the failure path the words are the thing worth keeping. + */ + fun proposePost( + localChatRoom: LocalChatRoom, + noteField: TextFieldState, + onSuccess: (sessionId: String) -> Unit, + onEmpty: () -> Unit, + onFailure: () -> Unit + ) { + // Guard against double submits. Posts accumulate rather than replace, so a + // second session over the same words is a second post on the record forever. + if (isActionPending.value) return + + val note = noteField.text.toString().trim() + // The line every member's device declines on too, so a proposal this + // composer sends is never one the group refuses. GroupStatementRefusal. + if (GroupStatementRefusal.isBlankPost(note)) { + onEmpty.invoke() + return + } + + isActionPending.value = true + + val template = GroupPost.template(note) + + viewModelScope.launch(Dispatchers.IO) { + val session = runCatching { + frostSigningRepository.proposeSigning( + localChatRoom = localChatRoom, + userPublicKey = activeUserPublicKey, + kind = template.kind, + tags = template.tags, + content = template.content, + ) + }.onFailure { error -> + logger.e("Failed to propose a post for $chatRoomId", error) + }.getOrNull() + + viewModelScope.launch(Dispatchers.Main) { + if (session != null) { + onSuccess.invoke(session.id) + } else { + onFailure.invoke() + } + } + + isActionPending.value = false + } + } + + companion object { + private const val TAG = "AddGroupPostViewModel" + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + initialAddGroupPostUIState: AddGroupPostUIState = AddGroupPostUIState.Loading, + chatRepository: ChatRepository, + frostSigningRepository: FrostSigningRepository + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + AddGroupPostViewModel( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = relayHint, + initialAddGroupPostUIState = initialAddGroupPostUIState, + chatRepository = chatRepository, + frostSigningRepository = frostSigningRepository + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index 55a29d13..036a8462 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -131,6 +131,7 @@ class ChatRoomDetailViewModel( parentChatRoomId = chatRepository.parentOf(chatRoomId), canAddSubgroup = canSign && !subgroupsNeedAWallet, groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), + groupPosts = chatRepository.groupPosts(chatRoomId), canProposeAsGroup = canSign && roomIsOpen, subgroupsNeedAWallet = canSign && subgroupsNeedAWallet, canGovern = canGovern, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupPostsViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupPostsViewModel.kt new file mode 100644 index 00000000..7e7a9c29 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupPostsViewModel.kt @@ -0,0 +1,64 @@ +package mobi.giza.compose.ui.view.model + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.launch +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.ui.view.state.GroupPostsUIState + +/** + * The group's posts, read once for the screen that shows them, with the + * profile that bylines them. One read rather than a watch, for the reason + * `GroupNostrProfileViewModel` gives. + */ +class GroupPostsViewModel( + val chatRoomId: String, + initialGroupPostsUIState: GroupPostsUIState, + val chatRepository: ChatRepository, +): ViewModel() { + + var groupPostsUIState: GroupPostsUIState by mutableStateOf(initialGroupPostsUIState) + private set + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) + + groupPostsUIState = if (localChatRoom == null) { + GroupPostsUIState.Error("Couldn't find the group") + } else { + GroupPostsUIState.Loaded( + localChatRoom = localChatRoom, + groupPosts = chatRepository.groupPosts(chatRoomId), + groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), + canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && + chatRepository.canSign(chatRoomId), + ) + } + } + } + + companion object { + fun factory( + chatRoomId: String, + initialGroupPostsUIState: GroupPostsUIState = GroupPostsUIState.Loading, + chatRepository: ChatRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + GroupPostsViewModel( + chatRoomId = chatRoomId, + initialGroupPostsUIState = initialGroupPostsUIState, + chatRepository = chatRepository, + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/AddGroupPostUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/AddGroupPostUIState.kt new file mode 100644 index 00000000..3fa81c34 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/AddGroupPostUIState.kt @@ -0,0 +1,33 @@ +package mobi.giza.compose.ui.view.state + +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.GroupNostrProfile + +sealed interface AddGroupPostUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + /** + * Who the group says it is, for the byline over the draft. + * + * A post is signed by the group and read as the group, so the composer + * shows whose voice is being written in -- which is not the member typing. + * Null in a group that has not described itself, and the byline falls back + * to the room. + */ + val groupNostrProfile: GroupNostrProfile? = null, + /** + * Whether this device holds a share of the group's key. + * + * False leaves the draft writable and the button inert, for the same reason + * the other two editors do: reading and composing cost nothing, and only a + * share-holder can open the session that would sign it. + */ + val canSign: Boolean = false, + ): AddGroupPostUIState + + data class Error( + val message: String + ): AddGroupPostUIState + + data object Loading: AddGroupPostUIState +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index 46c1b0bb..69b547d3 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -6,6 +6,7 @@ import mobi.giza.compose.managers.SubgroupManager import mobi.giza.compose.database.model.GroupSignedEvent import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.nostr.GroupPost sealed interface ChatRoomDetailUIState { data class Loaded( @@ -66,6 +67,11 @@ sealed interface ChatRoomDetailUIState { * none. docs/group-nostr-profile-and-posts.md. */ val groupNostrProfile: GroupNostrProfile? = null, + /** + * The kind:1s the group signed as itself, newest first, as many as this + * device holds. docs/group-nostr-profile-and-posts.md. + */ + val groupPosts: List = emptyList(), /** * Whether this device could put a profile or a post to the group's quorum: * a Marmot room it has not left, not disbanded, where it holds a share of diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupPostsUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupPostsUIState.kt new file mode 100644 index 00000000..6e6bcc1f --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupPostsUIState.kt @@ -0,0 +1,40 @@ +package mobi.giza.compose.ui.view.state + +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.nostr.GroupPost + +sealed interface GroupPostsUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + /** + * What the group has said publicly, as itself, newest first. Empty in + * a group that has said nothing, which is every group until somebody + * proposes a post. + */ + val groupPosts: List = emptyList(), + /** + * The group's profile, for the byline on every post. + * + * Read alongside the posts because a post is the one thing here a + * reader might otherwise attribute to whichever member proposed it, + * and the group's own name and picture are what say it was the group. + * Null where the group has not described itself, and the byline falls + * back to the key. + */ + val groupNostrProfile: GroupNostrProfile? = null, + /** + * Whether this device holds a share of the group's key. + * + * False leaves the posts readable and hides the way into the composer, + * for the reason `GroupNostrProfileUIState.Loaded.canSign` gives. + */ + val canSign: Boolean = false, + ): GroupPostsUIState + + data class Error( + val message: String + ): GroupPostsUIState + + data object Loading: GroupPostsUIState +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupPostsScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupPostsScreenJvmTest.kt new file mode 100644 index 00000000..40ae2a83 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupPostsScreenJvmTest.kt @@ -0,0 +1,146 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.getBoundsInRoot +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.runDesktopComposeUiTest +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.nostr.GroupPost +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey +import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId +import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.post +import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.profile +import mobi.giza.compose.ui.composable.navigation.routes.AddGroupPostRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.view.state.GroupPostsUIState +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The group's posts on their own screen: newest first and whole, under the + * group's name, and the composer for a member holding a share. + * docs/group-nostr-profile-and-posts.md. + */ +@OptIn(ExperimentalTestApi::class) +class GroupPostsScreenJvmTest { + + @Test + fun `the posts are drawn newest first, under the group's name`() = render( + state(posts = listOf(post("The second thing", 1_700_000_900), post("The first thing", 1_700_000_000))) + ) { + // Newest first, and whole rather than previewed -- a post is the one thing + // the group signs that exists to be read. + val newest = onNodeWithText("The second thing").getBoundsInRoot().top + val oldest = onNodeWithText("The first thing").getBoundsInRoot().top + assertTrue(newest < oldest, "the posts were drawn oldest first") + + // Under the group's name, not the member's. The whole point of signing a + // post as the group is that no member can be blamed for it. Once per + // post: there is no profile card on this screen to add a third. + onAllNodesWithText("Translation collective").assertCountEquals(2) + onNodeWithText("Add post").assertIsDisplayed() + } + + @Test + fun `a group that has not described itself bylines its posts with the key`() = render( + state(posts = listOf(post("Something the group said", 1_700_000_000)), groupNostrProfile = null) + ) { + onNodeWithText("Something the group said").assertIsDisplayed() + onNodeWithText(chatRoomId.take(16).chunked(8).joinToString(" ")).assertIsDisplayed() + } + + @Test + fun `a group that has posted nothing says so, and offers to post`() { + var opened: Route? = null + + render(state(posts = emptyList()), onNavigateToRoute = { opened = it }) { + onNodeWithText("This device holds no posts by this group", substring = true).assertIsDisplayed() + onNodeWithText("Add post").assertIsDisplayed().performClick() + } + + assertEquals(AddGroupPostRoute(activeUserPublicKey, chatRoomId, relayHint = null), opened) + } + + @Test + fun `a member holding no share of the key reads the posts and is offered no composer`() = render( + state(posts = listOf(post("Something the group said", 1_700_000_000)), canSign = false) + ) { + // A post is the one thing here that is meant to be read by people who + // were not in the room, so a member without a share reads it like + // anybody else and simply cannot propose the next one. + onNodeWithText("Something the group said").assertIsDisplayed() + onNodeWithText("Add post").assertDoesNotExist() + } + + @Test + fun `an identity that cannot sign is offered no composer`() = render( + state(posts = listOf(post("Something the group said", 1_700_000_000))), + identityCanSign = false, + ) { + // An npub-only profile cannot send the proposal at all. docs/npub-sign-in.md. + onNodeWithText("Something the group said").assertIsDisplayed() + onNodeWithText("Add post").assertDoesNotExist() + } + + @Test + fun `a group that has posted nothing offers no composer to a member holding no share`() = render( + state(posts = emptyList(), canSign = false) + ) { + onNodeWithText("This device holds no posts by this group", substring = true).assertIsDisplayed() + onNodeWithText("Add post").assertDoesNotExist() + } + + private fun state( + posts: List, + groupNostrProfile: GroupNostrProfile? = profile, + canSign: Boolean = true + ) = GroupPostsUIState.Loaded( + localChatRoom = GroupSignedWorkFixtures.localChatRoom(), + groupPosts = posts, + groupNostrProfile = groupNostrProfile, + canSign = canSign + ) + + private fun render( + uiState: GroupPostsUIState, + onNavigateToRoute: (Route) -> Unit = {}, + identityCanSign: Boolean = true, + assertions: ComposeUiTest.() -> Unit + ) = runDesktopComposeUiTest(width = 400, height = 2000) { + setContent { + GizaTheme { + ProvideSnackbarHost { + CompositionLocalProvider(LocalCanSign provides identityCanSign) { + Box(modifier = Modifier.fillMaxSize()) { + GroupPostsScreen( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = null, + initialGroupPostsUIState = uiState, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + onNavigateToRoute = onNavigateToRoute, + onNavigateBack = {}, + ) + } + } + } + } + } + + assertions() + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt index 7e06c4ce..a6ec8d94 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt @@ -10,12 +10,15 @@ import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.runDesktopComposeUiTest import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.nostr.GroupPost import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.NostrRepository import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId +import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.post import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.profile import mobi.giza.compose.ui.composable.navigation.routes.GroupNostrProfileRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupPostsRoute import mobi.giza.compose.ui.composable.navigation.routes.Route import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost import mobi.giza.compose.ui.theme.GizaTheme @@ -25,7 +28,7 @@ import kotlin.test.assertEquals /** * The rows on the group's screen that lead to what the group says as itself on - * nostr: its profile (docs/group-nostr-profile-and-posts.md). + * nostr: its profile and its posts (docs/group-nostr-profile-and-posts.md). * * The relay lists were not brought back with them (D1), so their row stays absent. */ @@ -61,6 +64,41 @@ class GroupSignedWorkRowsJvmTest { onNodeWithText("Subgroups").assertIsDisplayed() } + @Test + fun `the posts row counts them, and opens them`() { + var opened: Route? = null + + render( + state( + groupNostrProfile = profile, + groupPosts = listOf(post("One", 1_700_000_000), post("Two", 1_700_000_100)), + ), + onNavigateToRoute = { opened = it }, + ) { + onNodeWithText("Posts").assertIsDisplayed() + onNodeWithText("2 posts").assertIsDisplayed().performClick() + } + + assertEquals(GroupPostsRoute(activeUserPublicKey, chatRoomId, relayHint = null), opened) + } + + @Test + fun `the posts row says when there are none, or one`() { + render(state(groupNostrProfile = null)) { + onNodeWithText("No posts yet").assertIsDisplayed() + } + render(state(groupNostrProfile = null, groupPosts = listOf(post("One", 1_700_000_000)))) { + onNodeWithText("1 post").assertIsDisplayed() + } + } + + @Test + fun `a NIP-17 room has no posts row either`() = render( + state(groupNostrProfile = null, mlsGroupState = null) + ) { + onNodeWithText("Posts").assertDoesNotExist() + } + @Test fun `there is no relays row`() = render(state(groupNostrProfile = profile)) { onNodeWithText("Relays").assertDoesNotExist() @@ -69,12 +107,14 @@ class GroupSignedWorkRowsJvmTest { private fun state( groupNostrProfile: GroupNostrProfile?, + groupPosts: List = emptyList(), mlsGroupState: String? = "state", canProposeAsGroup: Boolean = true, ) = ChatRoomDetailUIState.Loaded( localChatRoom = GroupSignedWorkFixtures.localChatRoom(mlsGroupState), groupKeyState = GroupSignedWorkFixtures.groupKeyState, groupNostrProfile = groupNostrProfile, + groupPosts = groupPosts, canProposeAsGroup = canProposeAsGroup, ) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/AddGroupPostViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/AddGroupPostViewModelJvmTest.kt new file mode 100644 index 00000000..3efb32c3 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/AddGroupPostViewModelJvmTest.kt @@ -0,0 +1,102 @@ +package mobi.giza.compose.ui.view.model + +import androidx.compose.foundation.text.input.TextFieldState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.FrostSigningRepository +import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures +import mobi.giza.compose.ui.view.state.AddGroupPostUIState + +/** + * What the composer puts to the group's quorum, and what it will not. + * docs/group-nostr-profile-and-posts.md, Phase 6. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class AddGroupPostViewModelJvmTest { + + @BeforeTest + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + } + + private val asked = mutableListOf>() + + private val repository = object : FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { + override suspend fun proposeSigning( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + kind: Kind, + tags: Array>, + content: String, + ): FrostSigningSession { + asked += kind to content + return FrostSigningSession( + id = "5e55".repeat(16), + chatRoomId = localChatRoom.chatRoom.id, + coordinatorPublicKey = userPublicKey, + userPublicKey = userPublicKey, + dkgSessionId = "c".repeat(64), + threshold = 2, + participantCount = 3, + signerId = 0, + ) + } + } + + private val viewModel = AddGroupPostViewModel( + chatRoomId = GroupSignedWorkFixtures.chatRoomId, + activeUserPublicKey = GroupSignedWorkFixtures.activeUserPublicKey, + relayHint = null, + initialAddGroupPostUIState = AddGroupPostUIState.Loading, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + frostSigningRepository = repository, + ) + + private fun propose(note: String): String = runBlocking { + val outcome = CompletableDeferred() + viewModel.proposePost( + localChatRoom = GroupSignedWorkFixtures.localChatRoom(), + noteField = TextFieldState(note), + onSuccess = { outcome.complete("proposed $it") }, + onEmpty = { outcome.complete("empty") }, + onFailure = { outcome.complete("failed") }, + ) + withTimeout(5_000) { outcome.await() } + } + + @Test + fun `a note is proposed as a bare kind 1, trimmed`() { + assertEquals("proposed ${"5e55".repeat(16)}", propose(" We meet on Thursday \n")) + assertEquals(listOf(TextNoteEvent.KIND to "We meet on Thursday"), asked) + } + + @Test + fun `a blank note is not proposed`() { + // A kind:1 is not replaceable, and every member's device would decline a + // blank one anyway (GroupStatementRefusal). + assertEquals("empty", propose(" \n ")) + assertTrue(asked.isEmpty(), "the group was asked to sign nothing") + } +}