diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 5b3a8349..34495a8d 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -592,4 +592,25 @@ Why this is unavailable Unavailable View profile + + About + Couldn't ask the group to sign this profile. + Edit Nostr profile + eg. A group translating hard books into Sesotho + eg. group@example.com + eg. https://example.com + eg. https://example.com/group.png + eg. Translation collective + No name on this profile + Nostr address + Nostr profile + Picture URL + Propose Nostr profile + Signed by the group on %1$s + The group signs this, so it takes a quorum. An empty field unsays what the group had said. + This group has no shared key, so it cannot sign a profile. Run a shared key ceremony first. + Website + 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. 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 d2a48d34..2f1cead8 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.not_described_yet +import mobi.giza.compose.resources.no_name_on_this_profile +import mobi.giza.compose.resources.nostr_profile +import mobi.giza.compose.ui.composable.navigation.routes.GroupNostrProfileRoute +import mobi.giza.compose.nostr.GroupNostrProfile +import androidx.compose.material.icons.filled.Badge import androidx.compose.material3.ListItem import androidx.compose.ui.text.style.TextOverflow import androidx.compose.foundation.layout.Arrangement @@ -645,6 +651,34 @@ fun ChatRoomDetailScreen( HorizontalDivider() } + // What the group says about itself on nostr, as the group + // signed it (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 + // without a share -- and the screen behind it is where a + // member who holds one finds the editor. + if (chatRoomDetailUIState.localChatRoom.chatRoom.mlsGroupState != null) { + item { + GroupNostrProfileRow( + groupNostrProfile = chatRoomDetailUIState.groupNostrProfile, + onClick = { + onNavigateToRoute.invoke( + GroupNostrProfileRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = relayHint + ) + ) + } + ) + } + + item { + HorizontalDivider() + } + } + // The room's key, share by share (docs/frost-share-refresh.md, // Phase 11): which generation the group signs with, who // holds what, what this device is being asked, and the two @@ -1929,3 +1963,44 @@ private fun FoundingMembersCard( /** The founders [publicKeys] names, as the screen calls them, in a stable order. */ private fun ChatRoomDetailUIState.Loaded.founderNamesFor(publicKeys: Set): String = publicKeys.map { founderNames[it] ?: it }.sorted().joinToString(", ") + +/** + * The row on the group's screen that leads to its nostr profile: what the group is + * called and its nostr address, or that this device holds no profile for it. The + * signing-key card's shape, since both are the group's identity rather than its + * members' business. + */ +@Composable +private fun GroupNostrProfileRow( + groupNostrProfile: GroupNostrProfile?, + onClick: () -> Unit, +) { + Card( + modifier = Modifier.fillMaxWidth(), + onClick = onClick + ) { + ListItem( + leadingContent = { + Icon(Icons.Default.Badge, contentDescription = Decorative) + }, + trailingContent = { + Icon(Icons.Default.ChevronRight, contentDescription = Decorative) + }, + headlineContent = { + Text(text = stringResource(Res.string.nostr_profile)) + }, + supportingContent = { + Text( + text = groupNostrProfile?.let { profile -> + listOfNotNull( + profile.name() ?: stringResource(Res.string.no_name_on_this_profile), + profile.nip05() + ).joinToString(" · ") + } ?: stringResource(Res.string.not_described_yet), + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + ) + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt new file mode 100644 index 00000000..00211c4c --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt @@ -0,0 +1,393 @@ +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.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.rememberScrollState +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.Notes +import androidx.compose.material.icons.filled.AlternateEmail +import androidx.compose.material.icons.filled.Draw +import androidx.compose.material.icons.filled.Image +import androidx.compose.material.icons.filled.Link +import androidx.compose.material.icons.filled.Title +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.graphics.vector.ImageVector +import androidx.compose.ui.text.style.TextAlign +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.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.EditGroupNostrProfileViewModel +import mobi.giza.compose.ui.view.state.EditGroupNostrProfileUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.about +import mobi.giza.compose.resources.could_not_ask_the_group_to_sign_this_profile +import mobi.giza.compose.resources.edit_nostr_profile +import mobi.giza.compose.resources.eg_a_group_translating_hard_books +import mobi.giza.compose.resources.eg_group_example_com +import mobi.giza.compose.resources.eg_https_example_com +import mobi.giza.compose.resources.eg_https_example_com_group_png +import mobi.giza.compose.resources.eg_translation_collective +import mobi.giza.compose.resources.name +import mobi.giza.compose.resources.nostr_address +import mobi.giza.compose.resources.picture_url +import mobi.giza.compose.resources.propose_nostr_profile +import mobi.giza.compose.resources.the_group_signs_its_profile_so_it_takes_a_quorum +import mobi.giza.compose.resources.this_group_has_no_shared_key_to_sign_a_profile +import mobi.giza.compose.resources.website +import mobi.giza.compose.resources.what_the_group_says_about_itself_on_nostr +import org.jetbrains.compose.resources.stringResource + +/** + * The form for what a group says about itself on nostr. + * + * A group's kind:0 is signed by the group, so pressing the button proposes rather + * than saves: the form goes out as one event for the room's quorum to put its key + * to, and the screen hands over to the signing session it opened. Nothing about the + * profile has changed by the time this screen closes. + * + * The fields start at what the group already says, so an edit is an edit. And they + * are sent as they stand -- **an emptied field clears what the group had said**, + * which is the only way to unsay something a group has signed. Fields this form + * does not offer are carried across untouched; see `GroupNostrProfile.template`. + * + * There is no lightning address on it. Giza keeps no wallet, and offering a payment + * address on the group's behalf would invite payments it cannot route or see; one + * already on the group's profile is kept through an edit. D6 of + * docs/group-nostr-profile-and-posts.md. + */ +@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) +@Composable +fun EditGroupNostrProfileScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + initialEditGroupNostrProfileUIState: EditGroupNostrProfileUIState = + EditGroupNostrProfileUIState.Loading, + chatRepository: ChatRepository, + frostSigningRepository: FrostSigningRepository, + onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val editGroupNostrProfileViewModel: EditGroupNostrProfileViewModel = viewModel( + factory = EditGroupNostrProfileViewModel.factory( + chatRoomId = chatRoomId, + relayHint = relayHint, + initialEditGroupNostrProfileUIState = initialEditGroupNostrProfileUIState, + 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 the 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_profile) + + ScreenStateTransition(editGroupNostrProfileViewModel.editGroupNostrProfileUIState) { uiState -> + when (val editGroupNostrProfileUIState = uiState) { + is EditGroupNostrProfileUIState.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 = editGroupNostrProfileUIState.message, + onRetry = null + ) + } + + is EditGroupNostrProfileUIState.Loaded -> { + val profile = editGroupNostrProfileUIState.groupNostrProfile + + // Seeded from the profile the group already signed, so the form is + // an edit of it. `rememberTextFieldState` saves what is typed, which + // is what survives a rotation with the edits intact. + val nameFieldState = rememberTextFieldState(profile?.name() ?: "") + val aboutFieldState = rememberTextFieldState(profile?.about() ?: "") + val pictureFieldState = rememberTextFieldState(profile?.picture() ?: "") + val websiteFieldState = rememberTextFieldState(profile?.website() ?: "") + val nip05FieldState = rememberTextFieldState(profile?.nip05() ?: "") + + // 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 = editGroupNostrProfileUIState.canSign && LocalCanSign.current + + // imePadding: this screen is nothing but text fields, and without it + // the software keyboard covers whichever one is being typed into. + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + modifier = Modifier.imePadding(), + topBar = { + TopAppBar( + title = { + editGroupNostrProfileUIState.localChatRoom + .RenderChatRoomTitleText() + }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + bottomBar = { + BottomAppBar( + actions = {}, + floatingActionButton = { + ExtendedFab( + label = stringResource(Res.string.propose_nostr_profile), + icon = { Icon(Icons.Default.Draw, contentDescription = "Propose nostr profile") }, + enabled = canSign, + onClick = { + editGroupNostrProfileViewModel.proposeNostrProfile( + localChatRoom = + editGroupNostrProfileUIState.localChatRoom, + groupNostrProfile = profile, + nameField = nameFieldState, + aboutField = aboutFieldState, + pictureField = pictureFieldState, + websiteField = websiteFieldState, + nip05Field = nip05FieldState, + onSuccess = { sessionId -> + // Onto the session rather than back + // to the group. The profile has not + // changed yet -- it changes when a + // quorum signs -- so landing on a + // group still showing the old one + // would read as a failure. + onNavigateToRouteAndPopUpInclusive.invoke( + FrostSigningRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + sessionId = sessionId + ) + ) + }, + // Stay on the form with what was typed + // still in it. The proposal is what + // failed, and every word of it is worth + // keeping for the retry. + onFailure = { notify(couldNotPropose) } + ) + } + ) + } + ) + } + ) { innerPadding -> + Column( + modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Text(stringResource(Res.string.what_the_group_says_about_itself_on_nostr)) + + Text( + text = stringResource( + Res.string.the_group_signs_its_profile_so_it_takes_a_quorum + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center + ) + + if (!editGroupNostrProfileUIState.canSign) { + Text( + text = stringResource( + Res.string.this_group_has_no_shared_key_to_sign_a_profile + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + textAlign = TextAlign.Center + ) + } + + NostrProfileField( + state = nameFieldState, + icon = Icons.Default.Title, + iconDescription = "Name of the group", + label = stringResource(Res.string.name), + placeholder = stringResource(Res.string.eg_translation_collective) + ) + + NostrProfileField( + state = aboutFieldState, + icon = Icons.AutoMirrored.Filled.Notes, + iconDescription = "What the group is for", + label = stringResource(Res.string.about), + placeholder = stringResource( + Res.string.eg_a_group_translating_hard_books + ), + // The one field with prose in it, and the only one a + // single line would truncate while it was being typed. + lineLimits = TextFieldLineLimits.MultiLine(maxHeightInLines = 3) + ) + + NostrProfileField( + state = pictureFieldState, + icon = Icons.Default.Image, + iconDescription = "Picture of the group", + label = stringResource(Res.string.picture_url), + placeholder = stringResource(Res.string.eg_https_example_com_group_png) + ) + + NostrProfileField( + state = websiteFieldState, + icon = Icons.Default.Link, + iconDescription = "Website of the group", + label = stringResource(Res.string.website), + placeholder = stringResource(Res.string.eg_https_example_com) + ) + + NostrProfileField( + state = nip05FieldState, + icon = Icons.Default.AlternateEmail, + iconDescription = "Nostr address of the group", + label = stringResource(Res.string.nostr_address), + placeholder = stringResource(Res.string.eg_group_example_com) + ) + } + } + } + + EditGroupNostrProfileUIState.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.edit_nostr_profile), + style = MaterialTheme.typography.bodyLarge, + textAlign = TextAlign.Center + ) + + LoadingDataIndicator(fillScreen = false) + } + } + } + } + + LaunchedEffect(true) { + if (initialEditGroupNostrProfileUIState == EditGroupNostrProfileUIState.Loading) { + editGroupNostrProfileViewModel.initiateEditGroupNostrProfile() + } + } +} + +/** + * One field of the profile, in the shape the app's other forms use. + * + * Five of these on one screen is what makes it worth a function: the borderless + * outlined field over the bottom bar's tint is four lines of colours apiece, and + * five copies of that is where a divergence hides. + */ +@Composable +private fun NostrProfileField( + state: TextFieldState, + icon: ImageVector, + iconDescription: String, + label: String, + placeholder: String, + lineLimits: TextFieldLineLimits = TextFieldLineLimits.SingleLine +) { + OutlinedTextField( + modifier = Modifier.fillMaxWidth().background(BottomAppBarDefaults.containerColor), + state = state, + lineLimits = lineLimits, + colors = OutlinedTextFieldDefaults.colors( + focusedBorderColor = Color.Transparent, + unfocusedBorderColor = Color.Transparent, + disabledBorderColor = Color.Transparent + ), + leadingIcon = { + Icon(icon, contentDescription = iconDescription) + }, + label = { + Text(text = label) + }, + placeholder = { + Text(text = placeholder) + } + ) +} + +@ConformancePreviews +@Composable +private fun EditGroupNostrProfileScreenPreview() { + GizaTheme { + Surface( + modifier = Modifier.fillMaxSize() + ) { + EditGroupNostrProfileScreen( + activeUserPublicKey = "", + chatRoomId = "publicKey", + relayHint = null, + initialEditGroupNostrProfileUIState = EditGroupNostrProfileUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom( + id = "publicKey", + userPublicKey = "", + subject = "Translation collective", + description = "A group translating hard books.", + initialGiftWrapPayloadId = "sdfaer", + mlsGroupState = "state" + ), + ), + // A group that can sign, so the form 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/GroupNostrProfileScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupNostrProfileScreen.kt new file mode 100644 index 00000000..9540c8aa --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupNostrProfileScreen.kt @@ -0,0 +1,337 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +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.material.icons.Icons +import androidx.compose.material.icons.filled.Badge +import androidx.compose.material3.Card +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +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.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.edit_nostr_profile +import mobi.giza.compose.resources.no_name_on_this_profile +import mobi.giza.compose.resources.nostr_profile +import mobi.giza.compose.resources.signed_by_the_group_on +import mobi.giza.compose.resources.this_device_holds_no_profile_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.toFormattedTimeAndDateString +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.ui.composable.navigation.routes.EditGroupNostrProfileRoute +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.GroupNostrProfileViewModel +import mobi.giza.compose.ui.view.state.GroupNostrProfileUIState +import kotlin.time.Instant + +/** + * What the group says about itself on nostr, as the group signed it. + * + * Pushed from its row on the group's screen, which names the profile and + * nothing more. This is where it is read: the card and -- for a member holding + * a share of the key -- the way into the editor. A device that holds no profile + * for the group says so, and offers the editor from the same place. + * + * "Holds no profile", not "has none": the group's signed work is not handed to + * a member who joined after it was signed (docs/group-nostr-profile-and-posts.md, + * D8), so a late member's screen cannot tell a group that never described itself + * from one that did before they came. + * + * The profile is worth reading either way; proposing one is a signature by the + * group, and `proposeSigningBatch` throws for a device holding no share of the + * key. The editor is hidden rather than disabled, the way every gated way in + * on the group's screen is. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GroupNostrProfileScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + initialGroupNostrProfileUIState: GroupNostrProfileUIState = GroupNostrProfileUIState.Loading, + chatRepository: ChatRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val groupNostrProfileViewModel: GroupNostrProfileViewModel = viewModel( + factory = GroupNostrProfileViewModel.factory( + chatRoomId = chatRoomId, + initialGroupNostrProfileUIState = initialGroupNostrProfileUIState, + chatRepository = chatRepository, + ) + ) + + LaunchedEffect(true) { + if (initialGroupNostrProfileUIState == GroupNostrProfileUIState.Loading) { + groupNostrProfileViewModel.initiate() + } + } + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { + Text( + text = stringResource(Res.string.nostr_profile), + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + }, + navigationIcon = { NavigateBackButton(onNavigateBack) } + ) + } + ) { padding -> + ScreenStateTransition(groupNostrProfileViewModel.groupNostrProfileUIState) { uiState -> + when (val state = uiState) { + is GroupNostrProfileUIState.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 + ) + } + + GroupNostrProfileUIState.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 GroupNostrProfileUIState.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 edit: () -> Unit = { + onNavigateToRoute.invoke( + EditGroupNostrProfileRoute( + 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) + ) { + item { + state.groupNostrProfile?.let { groupNostrProfile -> + GroupNostrProfileCard( + groupNostrProfile = groupNostrProfile, + publicKey = chatRoomId + ) + } ?: EmptyState( + message = stringResource( + Res.string.this_device_holds_no_profile_for_this_group + ), + // The way to fill the absence, where this device + // could: describing the group is a signature by it. + action = if (canPropose) { + { EditNostrProfileButton(onClick = edit) } + } else { + null + } + ) + } + + if (canPropose && state.groupNostrProfile != null) { + item { + EditNostrProfileButton(onClick = edit) + } + } + } + } + } + } + } +} + +/** + * What the group says about itself on nostr, as the group signed it. + * + * A preview rather than a profile screen: the name, the picture, the nostr address + * and the first lines of the group's own account of itself, which is what a member + * opening the group's details came here to check. The whole thing is one signed + * event and the proposal list is where it can be read out in full. + * + * **The picture and the name come from the metadata; the tint comes from the key.** + * [publicKey] is the room's id, which is the pubkey the group signs as, so a group + * with no picture yet still gets the colour it has everywhere else in the app. + * + * The signing date is here because a group's profile is standing state with no + * other clue to its age -- and because the alternative reading, that this arrived + * from a relay a moment ago, is exactly what has not happened. Nothing on this card + * was published by being signed -- see `GroupNostrProfile`. + */ +@Composable +private fun GroupNostrProfileCard( + groupNostrProfile: GroupNostrProfile, + publicKey: HexKey +) { + Card(modifier = Modifier.fillMaxWidth()) { + ListItem( + leadingContent = { + ProfileAvatar( + publicKey = publicKey, + picture = groupNostrProfile.picture(), + name = groupNostrProfile.name() + ) + }, + headlineContent = { + Text( + // Named rather than falling back to the pubkey: the signing key + // row on the group's screen already shows that, and showing it + // twice would say the group has a name when it has not. + text = groupNostrProfile.name() + ?: stringResource(Res.string.no_name_on_this_profile), + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + }, + supportingContent = { + Column( + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) + ) { + groupNostrProfile.nip05()?.let { + Text( + text = it, + style = MaterialTheme.typography.labelMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + + groupNostrProfile.about()?.let { + Text( + text = it, + maxLines = 3, + overflow = TextOverflow.Ellipsis + ) + } + + Text( + text = stringResource( + Res.string.signed_by_the_group_on, + groupNostrProfile.signedAt.toFormattedTimeAndDateString() + ), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + ) + } +} + +/** The way into `EditGroupNostrProfileScreen`. The icon is decorative because the label is beside it. */ +@Composable +private fun EditNostrProfileButton(onClick: () -> Unit) { + TextButton(onClick = onClick) { + Icon(Icons.Default.Badge, contentDescription = Decorative) + + Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) + + Text(stringResource(Res.string.edit_nostr_profile)) + } +} + +@ConformancePreviews +@Composable +private fun GroupNostrProfileScreenPreview() { + GizaTheme { + Surface(modifier = Modifier.fillMaxSize()) { + GroupNostrProfileScreen( + activeUserPublicKey = "a".repeat(64), + chatRoomId = "d".repeat(64), + relayHint = null, + initialGroupNostrProfileUIState = GroupNostrProfileUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom( + id = "d".repeat(64), + userPublicKey = "a".repeat(64), + subject = "Translation room", + description = null, + initialGiftWrapPayloadId = "sdfaer", + mlsGroupState = "state" + ) + ), + // Built directly rather than read out of a signed event: the + // reading checks a signature, and there is no real one here. + groupNostrProfile = GroupNostrProfile( + signedEvent = GroupSignedEvent( + id = "e".repeat(64), + chatRoomId = "d".repeat(64), + publicKey = "d".repeat(64), + kind = MetadataEvent.KIND, + tags = emptyArray(), + content = "", + signature = "f".repeat(128), + createdAt = Instant.fromEpochSeconds(1_700_000_000) + ), + metadata = UserMetadata().apply { + displayName = "Translation collective" + about = "A group translating hard books into Sesotho." + nip05 = "group@example.com" + } + ), + 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 c6055c11..47a44286 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.EditGroupNostrProfileRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupNostrProfileRoute +import mobi.giza.compose.ui.composable.EditGroupNostrProfileScreen +import mobi.giza.compose.ui.composable.GroupNostrProfileScreen import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Surface import androidx.compose.material3.MaterialTheme @@ -1224,6 +1228,46 @@ fun GizaNavHost( }, ) } + // The group's nostr profile: docs/group-nostr-profile-and-posts.md. + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + GroupNostrProfileScreen( + 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() + + EditGroupNostrProfileScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + relayHint = route.relayHint, + chatRepository = databaseChatRepository, + frostSigningRepository = databaseFrostSigningRepository, + onNavigateToRouteAndPopUpInclusive = { signingRoute -> + // Replace the form so back returns to the profile rather + // than to an edit 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/EditGroupNostrProfileRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/EditGroupNostrProfileRoute.kt new file mode 100644 index 00000000..8e4114a0 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/EditGroupNostrProfileRoute.kt @@ -0,0 +1,11 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** The form that proposes the group's nostr profile for its quorum to sign. */ +@Serializable +data class EditGroupNostrProfileRoute( + 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/GroupNostrProfileRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupNostrProfileRoute.kt new file mode 100644 index 00000000..175be14a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupNostrProfileRoute.kt @@ -0,0 +1,18 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** + * What the group says about itself on nostr, as the group signed it. + * + * The group's screen names the profile in a row; this is where it is read, with, + * for a member holding a share of the key, the way into the editor. One of the two + * screens the group's public voice is split across -- see `GroupPostsRoute` -- each + * pushed from its row on the group's screen. docs/group-nostr-profile-and-posts.md. + */ +@Serializable +data class GroupNostrProfileRoute( + 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/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index 4e8964df..55a29d13 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 @@ -93,7 +93,7 @@ class ChatRoomDetailViewModel( // Initiate new chat... and navigate to new chat... ChatRoomDetailUIState.Error("Missing chat room") } else { - // One read of the capability for the two things that need it. It + // One read of the capability for the things that need it. It // walks the room's ceremonies looking for a share, so asking twice // would do the same walk twice for one answer. val canSign = localChatRoom.chatRoom.mlsGroupState != null && @@ -130,6 +130,8 @@ class ChatRoomDetailViewModel( subgroups = chatRepository.subgroupsOf(chatRoomId), parentChatRoomId = chatRepository.parentOf(chatRoomId), canAddSubgroup = canSign && !subgroupsNeedAWallet, + groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), + canProposeAsGroup = canSign && roomIsOpen, subgroupsNeedAWallet = canSign && subgroupsNeedAWallet, canGovern = canGovern, // The same rule `AddMemberToChatRoomConfirmationViewModel` enforces; diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModel.kt new file mode 100644 index 00000000..fef838bc --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModel.kt @@ -0,0 +1,158 @@ +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.nostr.GroupNostrProfile +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.FrostSigningRepository +import mobi.giza.compose.ui.view.state.EditGroupNostrProfileUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.launch + +/** + * Asks the group to sign what it says about itself on nostr. + * + * The room's id is the pubkey the group signs as, so the kind:0 this proposes is + * the profile the rest of nostr would read for that key -- authored by the group + * rather than by whoever filled the form in. Nothing is saved when the button is + * pressed: what goes out is a proposal, and the profile changes on every member's + * device at once when a quorum has signed it. + */ +class EditGroupNostrProfileViewModel( + val chatRoomId: String, + val activeUserPublicKey: HexKey, + val relayHint: String?, + initialEditGroupNostrProfileUIState: EditGroupNostrProfileUIState, + val chatRepository: ChatRepository, + val frostSigningRepository: FrostSigningRepository, +): ViewModel() { + + var editGroupNostrProfileUIState: EditGroupNostrProfileUIState by mutableStateOf( + initialEditGroupNostrProfileUIState + ) + private set + + private val logger = Logger.withTag(TAG) + + val isActionPending: MutableState = mutableStateOf(false) + + fun initiateEditGroupNostrProfile() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) + + editGroupNostrProfileUIState = if (localChatRoom == null) { + EditGroupNostrProfileUIState.Error("Couldn't find the chat room") + } else { + EditGroupNostrProfileUIState.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:0 for the group's own key. + * + * A blank field is not a field left alone: it clears what the group had said, + * because that is the only way to unsay it. [GroupNostrProfile.template] hands + * every field to `MetadataEvent`, whose rule for these arguments is that empty + * deletes the key -- and it builds on the group's newest profile, so a field + * this form does not offer is carried across rather than wiped. + * + * The fields are not cleared on success, unlike the add forms': a profile is + * standing state rather than a thing being added, and this screen is replaced + * by the signing session anyway. + */ + fun proposeNostrProfile( + localChatRoom: LocalChatRoom, + groupNostrProfile: GroupNostrProfile?, + nameField: TextFieldState, + aboutField: TextFieldState, + pictureField: TextFieldState, + websiteField: TextFieldState, + nip05Field: TextFieldState, + onSuccess: (sessionId: String) -> Unit, + onFailure: () -> Unit + ) { + // Guard against double submits from repeated taps. A second session over a + // second kind:0 would leave the group's profile decided by whichever + // quorum finished last. + if (isActionPending.value) return + isActionPending.value = true + + val template = GroupNostrProfile.template( + latest = groupNostrProfile, + name = nameField.text.toString().trim(), + about = aboutField.text.toString().trim(), + picture = pictureField.text.toString().trim(), + website = websiteField.text.toString().trim(), + nip05 = nip05Field.text.toString().trim(), + ) + + 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 nostr profile 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 = "EditGroupNostrProfileViewModel" + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + initialEditGroupNostrProfileUIState: EditGroupNostrProfileUIState = + EditGroupNostrProfileUIState.Loading, + chatRepository: ChatRepository, + frostSigningRepository: FrostSigningRepository + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + EditGroupNostrProfileViewModel( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = relayHint, + initialEditGroupNostrProfileUIState = initialEditGroupNostrProfileUIState, + chatRepository = chatRepository, + frostSigningRepository = frostSigningRepository + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupNostrProfileViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupNostrProfileViewModel.kt new file mode 100644 index 00000000..b7a0ed79 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupNostrProfileViewModel.kt @@ -0,0 +1,69 @@ +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.GroupNostrProfileUIState + +/** + * The group's nostr profile, read once for the screen that shows it. + * + * One read rather than a watch, the way the group's screen reads it: a profile + * changes when a quorum signs a new one, which lands as a group event this + * device processes, and the screen is re-entered -- and re-read -- on the way + * back from the signing session that made it. + */ +class GroupNostrProfileViewModel( + val chatRoomId: String, + initialGroupNostrProfileUIState: GroupNostrProfileUIState, + val chatRepository: ChatRepository, +): ViewModel() { + + var groupNostrProfileUIState: GroupNostrProfileUIState by mutableStateOf( + initialGroupNostrProfileUIState + ) + private set + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) + + groupNostrProfileUIState = if (localChatRoom == null) { + GroupNostrProfileUIState.Error("Couldn't find the group") + } else { + GroupNostrProfileUIState.Loaded( + localChatRoom = localChatRoom, + groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), + canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && + chatRepository.canSign(chatRoomId), + ) + } + } + } + + companion object { + fun factory( + chatRoomId: String, + initialGroupNostrProfileUIState: GroupNostrProfileUIState = + GroupNostrProfileUIState.Loading, + chatRepository: ChatRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + GroupNostrProfileViewModel( + chatRoomId = chatRoomId, + initialGroupNostrProfileUIState = initialGroupNostrProfileUIState, + chatRepository = chatRepository, + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupStatementCapability.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupStatementCapability.kt new file mode 100644 index 00000000..fbaaceff --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupStatementCapability.kt @@ -0,0 +1,44 @@ +package mobi.giza.compose.ui.view.model + +import com.vitorpamplona.marmot.groups.currentGroupState +import kotlinx.coroutines.CancellationException +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.MarmotProfile + +/** + * Whether a room is one the group can still speak as on nostr: put a profile or a post + * to its quorum (docs/group-nostr-profile-and-posts.md, D4). + * + * The share of the key is the other half, and the callers ask it themselves -- the + * detail screen already holds the answer and should not walk the ceremonies twice. + * This is the room's half: + * + * - **a Marmot room**: a NIP-17 room has no key of its own to sign as, so it has no + * nostr identity to describe; + * - **not left**: a member who left can no longer send the proposal into the group; + * - **not disbanded**: a group that has ended and signs a profile after it says + * something false. + * + * No admin check, as in Curare: proposing costs nothing but the quorum's attention, and + * the quorum decides. Nor a governance one: a profile is a signed event, not a commit. + */ +internal object GroupStatementCapability { + fun roomIsOpen(localChatRoom: LocalChatRoom): Boolean { + val chatRoom = localChatRoom.chatRoom + if (chatRoom.mlsGroupState == null || chatRoom.leftGroupAt != null) return false + + val isDisbanded = try { + chatRoom.takeIf { it.marmotProfile() == MarmotProfile.CURRENT } + ?.toMlsGroup() + ?.currentGroupState() + ?.isDisbanded == true + } catch (e: CancellationException) { + throw e + } catch (_: Throwable) { + // A group state that will not load is not evidence the group ended. The + // proposal itself would fail on such a room, and say so. + false + } + return !isDisbanded + } +} 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 d416ab75..46c1b0bb 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 @@ -5,6 +5,7 @@ import mobi.giza.compose.database.model.GroupKeyState 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 sealed interface ChatRoomDetailUIState { data class Loaded( @@ -60,6 +61,20 @@ sealed interface ChatRoomDetailUIState { * missing and what to do about it. */ val canAddSubgroup: Boolean = false, + /** + * The kind:0 the group signed about itself, or null while this device holds + * none. docs/group-nostr-profile-and-posts.md. + */ + val groupNostrProfile: GroupNostrProfile? = null, + /** + * 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 + * the key (D4 of docs/group-nostr-profile-and-posts.md). Capability, not + * permission -- any member with a share may propose, and the quorum is what + * decides. The identity's own capability, an npub that cannot sign at all, + * is the screen's to add: it is a composition local, not room state. + */ + val canProposeAsGroup: Boolean = false, /** * Whether this device could open a subgroup here but for the room's own * certificate saying `wallet=guarded`: a guarded group's subgroups are diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/EditGroupNostrProfileUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/EditGroupNostrProfileUIState.kt new file mode 100644 index 00000000..c8251286 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/EditGroupNostrProfileUIState.kt @@ -0,0 +1,34 @@ +package mobi.giza.compose.ui.view.state + +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.GroupNostrProfile + +sealed interface EditGroupNostrProfileUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + /** + * What the group has already said about itself, or null the first time. + * + * The form starts from it, and so does the event: an edit is built with + * `MetadataEvent.updateFromPast` so a field this app does not offer survives + * being edited rather than being dropped by it. See + * [GroupNostrProfile.template]. + */ + val groupNostrProfile: GroupNostrProfile? = null, + /** + * Whether this device holds a share of the group's key. + * + * False leaves the form readable and the button inert, which is the honest + * shape: the profile is worth reading either way, and a member without a + * share cannot open a session for one. See + * `ChatRoomDetailUIState.canProposeAsGroup`. + */ + val canSign: Boolean = false, + ): EditGroupNostrProfileUIState + + data class Error( + val message: String + ): EditGroupNostrProfileUIState + + data object Loading: EditGroupNostrProfileUIState +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupNostrProfileUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupNostrProfileUIState.kt new file mode 100644 index 00000000..4a54d105 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupNostrProfileUIState.kt @@ -0,0 +1,35 @@ +package mobi.giza.compose.ui.view.state + +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.GroupNostrProfile + +sealed interface GroupNostrProfileUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + /** + * The kind:0 the group signed about itself, or null while it has signed + * none. + * + * Null is an ordinary state and the screen says so -- a group has an + * identity from the moment it has a key and describes it whenever + * somebody gets round to it. + */ + val groupNostrProfile: GroupNostrProfile? = null, + /** + * Whether this device holds a share of the group's key. + * + * False leaves the profile readable and hides the way into the editor: + * proposing one is a signature by the group, and + * `FrostSigningManager.proposeSigningBatch` throws for a device holding + * no share. It is not about permission -- any member with a share may + * propose -- and the quorum is what decides. + */ + val canSign: Boolean = false, + ): GroupNostrProfileUIState + + data class Error( + val message: String + ): GroupNostrProfileUIState + + data object Loading: GroupNostrProfileUIState +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailWithoutWalletsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailWithoutWalletsJvmTest.kt index 7218f2b7..22759e8c 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailWithoutWalletsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailWithoutWalletsJvmTest.kt @@ -41,15 +41,6 @@ class ChatRoomDetailWithoutWalletsJvmTest { onNodeWithText("Subgroups").assertIsDisplayed() } - @Test - fun `the group's screen has no nostr profile, relays, posts or paste`() = render(state()) { - onNodeWithText("Nostr profile").assertDoesNotExist() - onNodeWithText("Relays").assertDoesNotExist() - onNodeWithText("Posts").assertDoesNotExist() - onNodeWithText("Propose event").assertDoesNotExist() - onNodeWithText("Subgroups").assertIsDisplayed() - } - @Test fun `a group that can sign offers a subgroup`() = render(state(canAddSubgroup = true)) { onNodeWithText("Add subgroup").assertIsDisplayed() diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupNostrProfileScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupNostrProfileScreenJvmTest.kt new file mode 100644 index 00000000..058f8c72 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupNostrProfileScreenJvmTest.kt @@ -0,0 +1,158 @@ +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.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.runDesktopComposeUiTest +import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata +import mobi.giza.compose.nostr.GroupNostrProfile +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.profile +import mobi.giza.compose.ui.composable.navigation.routes.EditGroupNostrProfileRoute +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.GroupNostrProfileUIState +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * The group's nostr profile on its own screen: what is drawn, and who is offered + * the editor. docs/group-nostr-profile-and-posts.md. + */ +@OptIn(ExperimentalTestApi::class) +class GroupNostrProfileScreenJvmTest { + + @Test + fun `the profile is drawn whole`() = render(state(groupNostrProfile = profile)) { + onNodeWithText("Translation collective").assertIsDisplayed() + onNodeWithText("group@example.com").assertIsDisplayed() + onNodeWithText("A group translating hard books into Sesotho.").assertIsDisplayed() + onAllNodesWithText("Signed by the group on", substring = true).assertCountEquals(1) + } + + /** docs/group-nostr-profile-and-posts.md, D6. */ + @Test + fun `a lightning address on the group's profile is not shown`() { + val withAddress = GroupNostrProfile( + signedEvent = profile.signedEvent, + metadata = UserMetadata().apply { + displayName = "Translation collective" + lud16 = "group@getalby.com" + } + ) + + render(state(groupNostrProfile = withAddress)) { + onNodeWithText("Translation collective").assertIsDisplayed() + onNodeWithText("group@getalby.com", substring = true).assertDoesNotExist() + } + } + + @Test + fun `a member holding a share of the key is offered the editor`() { + var opened: Route? = null + + render(state(groupNostrProfile = profile), onNavigateToRoute = { opened = it }) { + onNodeWithText("Edit Nostr profile").assertIsDisplayed().performClick() + } + + assertEquals( + EditGroupNostrProfileRoute(activeUserPublicKey, chatRoomId, relayHint = null), + opened + ) + } + + @Test + fun `a member holding no share of the key reads the profile and is offered no edit`() = render( + state(groupNostrProfile = profile, canSign = false) + ) { + // The profile is worth reading whoever is looking; proposing one needs a + // share, and `proposeSigningBatch` throws without one. + onNodeWithText("Translation collective").assertIsDisplayed() + onNodeWithText("Edit Nostr profile").assertDoesNotExist() + } + + @Test + fun `an identity that cannot sign is offered no edit`() = render( + state(groupNostrProfile = profile), + identityCanSign = false, + ) { + // An npub-only profile cannot send the proposal at all. docs/npub-sign-in.md. + onNodeWithText("Translation collective").assertIsDisplayed() + onNodeWithText("Edit Nostr profile").assertDoesNotExist() + } + + @Test + fun `a device holding no profile says so, and offers to write one`() = render( + state(groupNostrProfile = null) + ) { + // "Holds no profile", not "has none": a profile signed before this member + // joined is not passed on (D8). + onNodeWithText("This device holds no profile for this group", substring = true) + .assertIsDisplayed() + onNodeWithText("Edit Nostr profile").assertIsDisplayed() + } + + @Test + fun `a device holding no profile offers no editor to a member holding no share`() = render( + state(groupNostrProfile = null, canSign = false) + ) { + onNodeWithText("This device holds no profile for this group", substring = true) + .assertIsDisplayed() + onNodeWithText("Edit Nostr profile").assertDoesNotExist() + } + + private fun state( + groupNostrProfile: GroupNostrProfile?, + canSign: Boolean = true + ) = GroupNostrProfileUIState.Loaded( + localChatRoom = GroupSignedWorkFixtures.localChatRoom(), + groupNostrProfile = groupNostrProfile, + canSign = canSign + ) + + /** + * The screen at a phone's width. The state is passed in, so the NO_OP + * repository is never asked for anything: `initiate` only runs for a screen + * that arrives loading. + */ + private fun render( + uiState: GroupNostrProfileUIState, + 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()) { + GroupNostrProfileScreen( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = null, + initialGroupNostrProfileUIState = uiState, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + onNavigateToRoute = onNavigateToRoute, + onNavigateBack = {}, + ) + } + } + } + } + } + + assertions() + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkFixtures.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkFixtures.kt index b16495e0..62d9dd03 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkFixtures.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkFixtures.kt @@ -2,6 +2,12 @@ package mobi.giza.compose.ui.composable import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.GroupKeyState +import mobi.giza.compose.database.model.GroupSignedEvent +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.nostr.GroupPost +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import kotlin.time.Instant @@ -42,4 +48,37 @@ internal object GroupSignedWorkFixtures { announcedBy = chatRoomId, announcedAt = Instant.fromEpochSeconds(1_700_000_000) ) + + /** The group's nostr profile. docs/group-nostr-profile-and-posts.md. */ + val profile = GroupNostrProfile( + signedEvent = GroupSignedEvent( + id = "e".repeat(64), + chatRoomId = chatRoomId, + publicKey = chatRoomId, + kind = MetadataEvent.KIND, + tags = emptyArray(), + content = "", + signature = "f".repeat(128), + createdAt = Instant.fromEpochSeconds(1_700_000_000) + ), + metadata = UserMetadata().apply { + displayName = "Translation collective" + about = "A group translating hard books into Sesotho." + nip05 = "group@example.com" + } + ) + + /** One of the group's posts, at [createdAt]. */ + fun post(content: String, createdAt: Long) = GroupPost( + signedEvent = GroupSignedEvent( + id = createdAt.toString().padStart(64, 'b'), + chatRoomId = chatRoomId, + publicKey = chatRoomId, + kind = TextNoteEvent.KIND, + tags = emptyArray(), + content = content, + signature = "f".repeat(128), + createdAt = Instant.fromEpochSeconds(createdAt) + ) + ) } 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 new file mode 100644 index 00000000..7e06c4ce --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt @@ -0,0 +1,112 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsDisplayed +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.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.profile +import mobi.giza.compose.ui.composable.navigation.routes.GroupNostrProfileRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState +import kotlin.test.Test +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). + * + * The relay lists were not brought back with them (D1), so their row stays absent. + */ +@OptIn(ExperimentalTestApi::class) +class GroupSignedWorkRowsJvmTest { + + @Test + fun `a Marmot room names its profile, and the row opens it`() { + var opened: Route? = null + + render(state(groupNostrProfile = profile), onNavigateToRoute = { opened = it }) { + onNodeWithText("Nostr profile").assertIsDisplayed() + onNodeWithText("Translation collective · group@example.com").assertIsDisplayed() + .performClick() + } + + assertEquals(GroupNostrProfileRoute(activeUserPublicKey, chatRoomId, relayHint = null), opened) + } + + @Test + fun `a room whose profile this device does not hold says it is not described`() = render( + state(groupNostrProfile = null) + ) { + onNodeWithText("Nostr profile").assertIsDisplayed() + onNodeWithText("Not described yet").assertIsDisplayed() + } + + @Test + fun `a NIP-17 room has no nostr identity of its own to show`() = render( + state(groupNostrProfile = profile, mlsGroupState = null) + ) { + onNodeWithText("Nostr profile").assertDoesNotExist() + onNodeWithText("Subgroups").assertIsDisplayed() + } + + @Test + fun `there is no relays row`() = render(state(groupNostrProfile = profile)) { + onNodeWithText("Relays").assertDoesNotExist() + onNodeWithText("Subgroups").assertIsDisplayed() + } + + private fun state( + groupNostrProfile: GroupNostrProfile?, + mlsGroupState: String? = "state", + canProposeAsGroup: Boolean = true, + ) = ChatRoomDetailUIState.Loaded( + localChatRoom = GroupSignedWorkFixtures.localChatRoom(mlsGroupState), + groupKeyState = GroupSignedWorkFixtures.groupKeyState, + groupNostrProfile = groupNostrProfile, + canProposeAsGroup = canProposeAsGroup, + ) + + /** + * The screen at a phone's width and a window tall enough to compose the whole + * of it. The state is passed in, so the NO_OP repositories are never asked. + */ + private fun render( + uiState: ChatRoomDetailUIState, + onNavigateToRoute: (Route) -> Unit = {}, + assertions: ComposeUiTest.() -> Unit + ) = runDesktopComposeUiTest(width = 400, height = 4000) { + setContent { + GizaTheme { + ProvideSnackbarHost { + Box(modifier = Modifier.fillMaxSize()) { + ChatRoomDetailScreen( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = null, + initialChatRoomDetailUIState = uiState, + nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + onNavigateToRoute = onNavigateToRoute, + onPopBackToRoute = {}, + onNavigateBack = {}, + ) + } + } + } + } + + assertions() + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModelJvmTest.kt new file mode 100644 index 00000000..95539d54 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModelJvmTest.kt @@ -0,0 +1,159 @@ +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.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.time.Instant +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.GroupSignedEvent +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.GroupNostrProfile +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.EditGroupNostrProfileUIState + +/** + * What the profile form puts to the group's quorum: the event, not the screen. + * docs/group-nostr-profile-and-posts.md, Phase 5. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class EditGroupNostrProfileViewModelJvmTest { + + @BeforeTest + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + } + + private class Proposed(val kind: Kind, val content: String) + + /** A repository that records what it was asked to sign and opens a session for it. */ + private fun recording(proposed: CompletableDeferred) = + object : FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { + override suspend fun proposeSigning( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + kind: Kind, + tags: Array>, + content: String, + ): FrostSigningSession { + proposed.complete(Proposed(kind, 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 fun propose( + latest: GroupNostrProfile?, + name: String, + about: String = "", + nip05: String = "", + ): Pair = runBlocking { + val proposed = CompletableDeferred() + val sessionId = CompletableDeferred() + val viewModel = EditGroupNostrProfileViewModel( + chatRoomId = GroupSignedWorkFixtures.chatRoomId, + activeUserPublicKey = GroupSignedWorkFixtures.activeUserPublicKey, + relayHint = null, + initialEditGroupNostrProfileUIState = EditGroupNostrProfileUIState.Loading, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + frostSigningRepository = recording(proposed), + ) + + viewModel.proposeNostrProfile( + localChatRoom = GroupSignedWorkFixtures.localChatRoom(), + groupNostrProfile = latest, + nameField = TextFieldState(name), + aboutField = TextFieldState(about), + pictureField = TextFieldState(""), + websiteField = TextFieldState(""), + nip05Field = TextFieldState(nip05), + onSuccess = { sessionId.complete(it) }, + onFailure = { sessionId.completeExceptionally(AssertionError("the proposal failed")) }, + ) + + withTimeout(5_000) { proposed.await() to sessionId.await() } + } + + private fun existing(content: String) = GroupNostrProfile( + signedEvent = GroupSignedEvent( + id = "e".repeat(64), + chatRoomId = GroupSignedWorkFixtures.chatRoomId, + publicKey = GroupSignedWorkFixtures.chatRoomId, + kind = MetadataEvent.KIND, + tags = emptyArray(), + content = content, + signature = "f".repeat(128), + createdAt = Instant.fromEpochSeconds(1_700_000_000), + ), + metadata = UserMetadata(), + ) + + private fun read(content: String): UserMetadata = assertNotNull( + MetadataEvent("", "", 0, emptyArray(), content, "").contactMetaData() + ) + + @Test + fun `the form proposes a kind 0 with the name under both keys, and hands over its session`() { + val (proposed, sessionId) = propose(latest = null, name = " Translation collective ", about = "Hard books") + + assertEquals(MetadataEvent.KIND, proposed.kind) + val metadata = read(proposed.content) + assertEquals("Translation collective", metadata.name, "trimmed") + assertEquals("Translation collective", metadata.displayName) + assertEquals("Hard books", metadata.about) + assertEquals("5e55".repeat(16), sessionId) + } + + @Test + fun `an edit keeps what the form does not offer, a lightning address among it`() { + val latest = existing("""{"name":"Old","bot":true,"lud16":"group@getalby.com"}""") + + val (proposed, _) = propose(latest = latest, name = "New") + + val metadata = read(proposed.content) + assertEquals("New", metadata.name) + assertEquals(true, metadata.bot) + assertEquals("group@getalby.com", metadata.lud16, "D6: an edit made here must not wipe it") + } + + @Test + fun `an emptied field unsays what the group had said`() { + val latest = existing("""{"name":"Old","about":"Something regretted","nip05":"old@example.com"}""") + + val (proposed, _) = propose(latest = latest, name = "Old", about = "", nip05 = "") + + val metadata = read(proposed.content) + assertNull(metadata.about) + assertNull(metadata.nip05) + } +}