diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index fbb00063..8935984b 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -757,6 +757,52 @@ This device holds no such request for the confederation to sign Propose the charter The charter is the confederation's public statement of the groups it is made of, signed with its own key. It is how members who are not admins hear of it. + + Member of %1$s + Profile + The confederation has signed no profile yet + %1$d admins hold its key + Profile changes + Only the group's admins see proposed changes. + No changes to its profile have been proposed + Edit profile + How it was formed + Open the confederation's room + This device knows nothing of that confederation + This device holds no record of the confederation + This group is not one of the confederation's + This group cannot sign from this device + Only one of the group's admins can propose a change + Set up the group's inbox first: a change is sent from it + %1$s has no inbox, so it cannot be asked + Open + Endorsed, being signed + Published + Replaced by a newer profile + Declined + Withdrawn + Expired + Endorsed by %1$d of the %2$d groups it needs + Edit the confederation's profile + What the confederation says about itself on nostr + Your group's quorum signs the change, and it goes to every other group's inbox. The confederation signs it once %1$d of its %2$d groups have endorsed it. + Propose from + Propose to the groups + Couldn't propose the change + Profile change + This device does not hold that change + Endorse + Object + Withdraw the change + Endorsing lets the confederation's admins sign this profile once enough groups have endorsed it. Nobody is asked again. + Proposed it + Endorsed + Objected + Was: %1$s + Becomes: %1$s + Nothing + This change edits no field shown here + Being signed. Waiting on %1$s Inbox Inbox settings diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index a55b7774..2bbede15 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -334,6 +334,15 @@ class DatabaseChatRepository( override suspend fun confederationProposalCount(chatRoomId: String): Int = database.confederationDao().getProposalsNaming(chatRoomId).size + override suspend fun memberConfederations(chatRoomId: String): List> = try { + mobi.giza.compose.managers.ConfederationProfileManager.confederationsOf(database, chatRoomId).mapNotNull { id -> + mobi.giza.compose.managers.ConfederationProfileManager.membership(database, id)?.let { id to it.name } + } + } catch (e: Throwable) { + logger.e("Error reading the confederations of $chatRoomId", e) + emptyList() + } + override suspend fun canSignAsConfederation(chatRoomId: String): Boolean { if (!ExperimentalFeatures.confederation) return false val me = activeIdentity.value?.takeIf { it.canSign }?.nostrPublicKey ?: return false diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt index 810e4286..6112e78e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt @@ -17,6 +17,13 @@ import kotlinx.coroutines.flow.flowOf import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import mobi.giza.compose.managers.ConfederationProfileManager import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus +import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.managers.ConfederationProfileRefusal +import mobi.giza.compose.managers.FrostSigningManager +import mobi.giza.compose.managers.InboxReplies +import mobi.giza.compose.repository.ProfileChangeProblem +import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.Confederation import mobi.giza.compose.database.model.ConfederationCeremony @@ -124,6 +131,85 @@ class DatabaseConfederationRepository( ConfederationProfileManager.statusesFrom(rows, ConfederationProfileManager.profiles(database, confederationId), Clock.System.now().epochSeconds) } + override suspend fun membership(confederationId: HexKey): ConfederationProfileManager.Membership? = + ConfederationProfileManager.membership(database, confederationId) + + override fun observeProfile(confederationId: HexKey): Flow = + combine( + database.confederationDao().observeEventsForConfederation(confederationId), + database.groupSignedEventDao().observeCountByChatRoomIdAndKind(confederationId, MetadataEvent.KIND), + ) { _, _ -> Unit }.map { ConfederationProfileManager.profiles(database, confederationId).newestProfile } + + override suspend fun roleHolders(confederationId: HexKey): Map> = + ConfederationSigningManager.held(database, confederationId)?.plan?.let { plan -> + plan.groups.associateWith { group -> plan.seats.filter { it.group == group }.map { it.admin } } + } ?: emptyMap() + + override suspend fun formingProposalOf(confederationId: HexKey): HexKey? = + database.confederationCeremonyDao().getConfederation(confederationId)?.proposalId + + override suspend fun holdsRoomOf(confederationId: HexKey): Boolean = + database.chatRoomDao().findChatRoomById(confederationId) != null + + override suspend fun profileChangeProblem(chatRoomId: String, userPublicKey: HexKey, confederationId: HexKey): ProfileChangeProblem? { + val membership = ConfederationProfileManager.membership(database, confederationId) ?: return ProfileChangeProblem.NoRecord + if (!membership.includes(chatRoomId)) return ProfileChangeProblem.NotMember + val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return ProfileChangeProblem.NotMember + if (room.chatRoom.mlsGroupState == null || room.chatRoom.leftGroupAt != null) return ProfileChangeProblem.CannotSign + if (!FrostSigningManager.canSign(database, chatRoomId)) return ProfileChangeProblem.CannotSign + if (RoomAdmins.of(database, chatRoomId)?.admins?.contains(userPublicKey) != true) return ProfileChangeProblem.NotAdmin + if (ConfederationManager.announcedInboxKey(database, chatRoomId, userPublicKey) == null) return ProfileChangeProblem.NoInbox + membership.othersThan(chatRoomId).firstOrNull { !InboxReplies.hasAnnouncedKey(database, it) }?.let { + return ProfileChangeProblem.GroupWithoutInbox(ConfederationManager.nameOf(database, it)) + } + return null + } + + override suspend fun proposingGroupsFor(userPublicKey: HexKey, confederationId: HexKey): List { + val membership = ConfederationProfileManager.membership(database, confederationId) ?: return emptyList() + return membership.groups.filter { profileChangeProblem(it, userPublicKey, confederationId) == null } + } + + override suspend fun profileBaseOf(changeId: HexKey): UserMetadata? { + val change = ConfederationProfileManager.change(database, changeId) ?: return null + val profiles = ConfederationProfileManager.profiles(database, change.confederation) + val base = change.base?.let { id -> + database.confederationDao().getEvent(id)?.toEvent() + ?: database.groupSignedEventDao().getById(id)?.toEvent() + } + return base?.let(ConfederationProfileRefusal::metadataOf) ?: profiles.newestProfile?.metadata?.takeIf { change.base != null } + } + + override suspend fun proposeProfileChange( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + confederationId: HexKey, + tags: Array>, + content: String, + ): FrostSigningSession = ConfederationProfileManager.proposeChange(database, localChatRoom, userPublicKey, confederationId, tags, content) + + override suspend fun proposeProfileEndorsement(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey): FrostSigningSession = + ConfederationProfileManager.proposeEndorsement(database, localChatRoom, userPublicKey, changeId) + + override suspend fun proposeProfileObjection(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey, reason: String): FrostSigningSession = + ConfederationProfileManager.proposeObjection(database, localChatRoom, userPublicKey, changeId, reason) + + override fun observePendingProfileAnswer(chatRoomId: String, changeId: HexKey): Flow = + pendingProfileSession(chatRoomId) { rumor -> rumor.kind != ConfederationKinds.PROFILE_CHANGE && ConfederationProfileStatements.changeIdOf(rumor) == changeId } + + override fun observePendingProfileChange(chatRoomId: String, confederationId: HexKey): Flow = + pendingProfileSession(chatRoomId) { rumor -> rumor.kind == ConfederationKinds.PROFILE_CHANGE && ConfederationProfileStatements.confederationOf(rumor) == confederationId } + + private fun pendingProfileSession(chatRoomId: String, matches: (Event) -> Boolean): Flow = + database.frostSigningSessionDao().observeSessionsForChatRoom(chatRoomId).map { sessions -> + sessions.firstOrNull { local -> + local.session.stage != FrostSigningStage.COMPLETE && + local.session.stage != FrostSigningStage.FAILED && + ConfederationRefusal.Carried.from(database.confederationDao().getSigning(local.session.id)).rumor + ?.takeIf { it.kind in ConfederationKinds.PROFILE_CHANGE_KINDS }?.let(matches) == true + }?.session + } + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) override fun observeProfileChange(changeId: HexKey): Flow = database.confederationDao().observeEventsForProposal(changeId).map { rows -> diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index 43a14a6e..f9420fe0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -161,6 +161,13 @@ interface ChatRepository { */ suspend fun keyCeremonyOfRoom(chatRoomId: String): mobi.giza.compose.ui.view.state.KeyCeremonyLink? = null + /** + * The formed confederations the group of [chatRoomId] is a member of, as (id, name), by record or + * charter: what the group's screen lists, each opening the confederation's own screen. + * docs/confederation-profile.md, D1. + */ + suspend fun memberConfederations(chatRoomId: String): List> = emptyList() + /** The confederation whose room [chatRoomId] is, by name, if its record verifies here. docs/confederation.md, Phase 13. */ suspend fun confederationOfRoom(chatRoomId: String): String? = null diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt index 43ea9183..41d82b66 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt @@ -17,6 +17,9 @@ import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.managers.ConfederationManager import mobi.giza.compose.nostr.confederation.ConfederationStatus import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus +import mobi.giza.compose.managers.ConfederationProfileManager +import mobi.giza.compose.nostr.GroupNostrProfile +import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata /** * The confederation's events on this device, for the relay layer and the screens @@ -120,6 +123,55 @@ interface ConfederationRepository { /** One change to a confederation's profile, as it changes; null while this device does not hold it. */ fun observeProfileChange(changeId: HexKey): Flow = flowOf(null) + /** A formed confederation as this device knows it: by its record, or by its charter. docs/confederation-profile.md, D1. */ + suspend fun membership(confederationId: HexKey): ConfederationProfileManager.Membership? = null + + /** The newest profile the confederation has signed that this device holds, as it changes. */ + fun observeProfile(confederationId: HexKey): Flow = flowOf(null) + + /** Who holds the confederation's roles, by group: empty on a device that holds no record of it. */ + suspend fun roleHolders(confederationId: HexKey): Map> = emptyMap() + + /** The proposal the confederation was formed from, where this device holds it. */ + suspend fun formingProposalOf(confederationId: HexKey): HexKey? = null + + /** Whether this device holds the confederation's own room. */ + suspend fun holdsRoomOf(confederationId: HexKey): Boolean = false + + /** + * Why [userPublicKey] cannot put a change to [confederationId]'s profile to the group of + * [chatRoomId], or null when they can (D2). + */ + suspend fun profileChangeProblem(chatRoomId: String, userPublicKey: HexKey, confederationId: HexKey): ProfileChangeProblem? = + ProfileChangeProblem.NoRecord + + /** The member groups of [confederationId] this device is in whose statements [userPublicKey] can put to them. */ + suspend fun proposingGroupsFor(userPublicKey: HexKey, confederationId: HexKey): List = emptyList() + + /** What the change edits, read where this device holds it: the base, else the newest profile held. */ + suspend fun profileBaseOf(changeId: HexKey): UserMetadata? = null + + suspend fun proposeProfileChange( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + confederationId: HexKey, + tags: Array>, + content: String, + ): FrostSigningSession = throw UnsupportedOperationException("No confederation here") + + suspend fun proposeProfileEndorsement(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey): FrostSigningSession = + throw UnsupportedOperationException("No confederation here") + + /** An objection; from the group that proposed the change, its withdrawal. */ + suspend fun proposeProfileObjection(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey, reason: String): FrostSigningSession = + throw UnsupportedOperationException("No confederation here") + + /** A session in [chatRoomId]'s group over an answer to [changeId] that has not finished, if any: one at a time. */ + fun observePendingProfileAnswer(chatRoomId: String, changeId: HexKey): Flow = flowOf(null) + + /** A session in [chatRoomId]'s group proposing a change to [confederationId]'s profile that has not finished, if any. */ + fun observePendingProfileChange(chatRoomId: String, confederationId: HexKey): Flow = flowOf(null) + companion object { /** Holds nothing and proposes nothing: for screens and tests with no confederation behind them. */ val NO_OP_CONFEDERATION_REPOSITORY: ConfederationRepository = object : ConfederationRepository { @@ -165,3 +217,24 @@ interface ConfederationRepository { } } } + +/** Why a member cannot put a change to a confederation's profile to their group (docs/confederation-profile.md, D2). */ +sealed interface ProfileChangeProblem { + /** This device knows neither the confederation's record nor its charter. */ + data object NoRecord : ProfileChangeProblem + + /** This group is not one of the confederation's. */ + data object NotMember : ProfileChangeProblem + + /** The room is closed, or this device holds no share of the group's key. */ + data object CannotSign : ProfileChangeProblem + + /** The member is not one of the group's admins. */ + data object NotAdmin : ProfileChangeProblem + + /** This device does not hold the inbox key the group has announced. */ + data object NoInbox : ProfileChangeProblem + + /** Another member group has announced no inbox, so it cannot be asked. */ + data class GroupWithoutInbox(val name: String) : ProfileChangeProblem +} 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 c0900421..18fdaf63 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 @@ -21,6 +21,7 @@ import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxSettingsRoute import mobi.giza.compose.ui.view.state.InboxRowSummary import androidx.compose.material.icons.filled.Mail import mobi.giza.compose.ui.composable.navigation.routes.ConfederationsRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRoute import mobi.giza.compose.ui.composable.navigation.routes.GroupDmSetupRoute import mobi.giza.compose.ui.view.state.GroupDmRow import androidx.compose.material.icons.filled.Mail @@ -34,6 +35,7 @@ import mobi.giza.compose.resources.only_its_admins_read_them import mobi.giza.compose.ExperimentalFeatures import androidx.compose.material.icons.filled.Hub import mobi.giza.compose.resources.confederations +import mobi.giza.compose.resources.member_of_confederation import mobi.giza.compose.resources.no_confederations_yet import mobi.giza.compose.resources.one_confederation_proposal import mobi.giza.compose.resources.n_confederation_proposals @@ -828,6 +830,26 @@ fun ChatRoomDetailScreen( } } + // Each formed confederation this group is in, which opens it: its + // profile, its groups, and the changes to its profile. + // docs/confederation-profile.md, D1. + chatRoomDetailUIState.memberConfederations.forEach { (confederationId, name) -> + item { + MemberConfederationRow( + name = name, + onClick = { + onNavigateToRoute.invoke( + ConfederationRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + confederationId = confederationId, + ) + ) + }, + ) + } + } + if (ExperimentalFeatures.confederation) { item { ConfederationsRow( @@ -2313,6 +2335,24 @@ private fun GroupInboxRow( } /** The row that opens a group's confederations: how many proposals name it. docs/confederation.md. */ +/** A formed confederation this group is a member of. docs/confederation-profile.md, D1. */ +@Composable +private fun MemberConfederationRow( + name: String, + onClick: () -> Unit, +) { + Card( + modifier = Modifier.fillMaxWidth(), + onClick = onClick + ) { + ListItem( + leadingContent = { Icon(Icons.Default.Hub, contentDescription = Decorative) }, + trailingContent = { Icon(Icons.Default.ChevronRight, contentDescription = Decorative) }, + headlineContent = { Text(text = stringResource(Res.string.member_of_confederation, name), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + ) + } +} + @Composable private fun ConfederationsRow( proposalCount: Int, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt index 9063786e..5aca100b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt @@ -50,6 +50,8 @@ import mobi.giza.compose.repository.DkgRepository import mobi.giza.compose.repository.FrostSigningRepository import mobi.giza.compose.repository.NostrRepository import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProfileChangeRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRoute import mobi.giza.compose.ui.composable.navigation.routes.ChatRoomDetailRoute import mobi.giza.compose.ui.composable.navigation.routes.DkgRitualRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRitualRoute @@ -221,6 +223,16 @@ fun ChatRoomMessagingScreen( ConfederationSigningRoute(activeUserPublicKey = activeUserPublicKey, attemptId = attemptId) ) }, + onOpenConfederationProfileChange = { changeId -> + onNavigateToRoute.invoke( + ConfederationProfileChangeRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, changeId = changeId) + ) + }, + onOpenConfederation = { confederationId -> + onNavigateToRoute.invoke( + ConfederationRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, confederationId = confederationId) + ) + }, onOpenSigning = { sessionId -> onNavigateToRoute.invoke( proposalDestination( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileChangeScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileChangeScreen.kt new file mode 100644 index 00000000..491ce713 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileChangeScreen.kt @@ -0,0 +1,295 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +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.rememberTextFieldState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Block +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.HourglassEmpty +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +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.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberCoroutineScope +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 kotlin.time.Instant +import mobi.giza.compose.extensions.toFormattedTimeAndDateString +import mobi.giza.compose.nostr.confederation.ConfederationProfileAnswer +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.about +import mobi.giza.compose.resources.answer_endorsed +import mobi.giza.compose.resources.answer_objected +import mobi.giza.compose.resources.answer_proposed +import mobi.giza.compose.resources.answer_waiting +import mobi.giza.compose.resources.being_signed_waiting_on +import mobi.giza.compose.resources.confederation_groups +import mobi.giza.compose.resources.confederation_proposed_by +import mobi.giza.compose.resources.could_not_ask_the_group_to_answer +import mobi.giza.compose.resources.endorse +import mobi.giza.compose.resources.endorsing_lets_the_confederation_sign +import mobi.giza.compose.resources.n_of_m_endorsements +import mobi.giza.compose.resources.name +import mobi.giza.compose.resources.no_field_changes +import mobi.giza.compose.resources.nostr_address +import mobi.giza.compose.resources.object_to_the_change +import mobi.giza.compose.resources.open_the_signing_session +import mobi.giza.compose.resources.open_until +import mobi.giza.compose.resources.picture_url +import mobi.giza.compose.resources.profile_change +import mobi.giza.compose.resources.profile_field_becomes +import mobi.giza.compose.resources.profile_field_empty +import mobi.giza.compose.resources.profile_field_was +import mobi.giza.compose.resources.reason_optional +import mobi.giza.compose.resources.this_device_does_not_hold_that_change +import mobi.giza.compose.resources.waiting_for_the_group_to_sign_its_answer +import mobi.giza.compose.resources.website +import mobi.giza.compose.resources.withdraw_the_change +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.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.rememberNotifier +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.ConfederationProfileChangeViewModel +import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState +import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState.FieldName +import org.jetbrains.compose.resources.stringResource + +/** + * One proposed change to a confederation's profile, seen from one of its groups + * (docs/confederation-profile.md, D3): what it would change, field by field, how every group has + * answered, and this group's answer. Answering is a group signature, so each button opens a signing + * session and the screen goes to it. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ConfederationProfileChangeScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + changeId: HexKey, + initialUIState: ConfederationProfileChangeUIState = ConfederationProfileChangeUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: ConfederationProfileChangeViewModel = viewModel( + factory = ConfederationProfileChangeViewModel.factory( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + changeId = changeId, + initialUIState = initialUIState, + chatRepository = chatRepository, + confederationRepository = confederationRepository, + ) + ) + LaunchedEffect(true) { + if (initialUIState == ConfederationProfileChangeUIState.Loading) viewModel.initiate() + } + + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotAnswer = stringResource(Res.string.could_not_ask_the_group_to_answer) + val identityCanSign = LocalCanSign.current + val reasonField = rememberTextFieldState() + val state by viewModel.uiState.collectAsState() + val toSession: (String) -> Unit = { sessionId -> + onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) + } + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + modifier = Modifier.imePadding(), + topBar = { + TopAppBar( + title = { Text(text = stringResource(Res.string.profile_change), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + ) { padding -> + ScreenStateTransition(state) { uiState -> + when (val current = uiState) { + is ConfederationProfileChangeUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = current.message, onRetry = null) + + ConfederationProfileChangeUIState.Loading -> LoadingDataIndicator(modifier = Modifier.padding(padding)) + + ConfederationProfileChangeUIState.NotHeld -> EmptyState( + modifier = Modifier.padding(padding), + message = stringResource(Res.string.this_device_does_not_hold_that_change), + ) + + is ConfederationProfileChangeUIState.Loaded -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + val change = current.status.change + val nameOf = { key: HexKey -> current.names[key] ?: key.take(12) } + + Text(text = current.confederationName, style = MaterialTheme.typography.headlineSmall) + Text(text = changeStateLabel(current.status.state), style = MaterialTheme.typography.labelLarge) + Text(text = stringResource(Res.string.confederation_proposed_by, nameOf(change.proposingGroup))) + Text(text = stringResource(Res.string.n_of_m_endorsements, current.status.endorsers.size, change.threshold)) + Text( + text = stringResource(Res.string.open_until, Instant.fromEpochSeconds(change.expiresAt).toFormattedTimeAndDateString()), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + // What it would change. + HorizontalDivider() + if (current.differences.isEmpty()) { + Text(stringResource(Res.string.no_field_changes)) + } + current.differences.forEach { field -> + val empty = stringResource(Res.string.profile_field_empty) + ListItem( + leadingContent = { Icon(Icons.Default.Edit, contentDescription = Decorative) }, + headlineContent = { Text(fieldLabel(field.name)) }, + supportingContent = { + Column { + Text( + text = stringResource(Res.string.profile_field_was, field.before ?: empty), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text(text = stringResource(Res.string.profile_field_becomes, field.after ?: empty)) + } + }, + ) + } + + // How every group has answered. + HorizontalDivider() + Text(text = stringResource(Res.string.confederation_groups), style = MaterialTheme.typography.titleSmall) + change.groups.forEach { group -> + val answer = current.status.answerOf(group) + ListItem( + leadingContent = { + Icon( + imageVector = when (answer) { + ConfederationProfileAnswer.PROPOSED, ConfederationProfileAnswer.ENDORSED -> Icons.Default.CheckCircle + ConfederationProfileAnswer.OBJECTED -> Icons.Default.Block + ConfederationProfileAnswer.WAITING -> Icons.Default.HourglassEmpty + }, + contentDescription = Decorative, + ) + }, + headlineContent = { Text(text = nameOf(group), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = { + Text( + stringResource( + when (answer) { + ConfederationProfileAnswer.PROPOSED -> Res.string.answer_proposed + ConfederationProfileAnswer.ENDORSED -> Res.string.answer_endorsed + ConfederationProfileAnswer.OBJECTED -> Res.string.answer_objected + ConfederationProfileAnswer.WAITING -> Res.string.answer_waiting + } + ) + (current.status.answers[group]?.reason?.takeIf { it.isNotBlank() }?.let { ": $it" } ?: "") + ) + }, + ) + } + + // Once enough groups have endorsed it: who the signing is still waiting on. + if (current.status.state == ConfederationProfileChangeState.ENDORSED) { + val unvouched = current.status.endorsers.filter { it !in current.status.vouchers.keys } + if (unvouched.isNotEmpty()) { + Text( + text = stringResource(Res.string.being_signed_waiting_on, unvouched.joinToString { nameOf(it) }), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + current.pendingSessionId?.let { sessionId -> + HorizontalDivider() + Text(text = stringResource(Res.string.waiting_for_the_group_to_sign_its_answer)) + TextButton(onClick = { toSession(sessionId) }) { Text(stringResource(Res.string.open_the_signing_session)) } + } + + if (current.canEndorseOrObject && identityCanSign) { + HorizontalDivider() + Text( + text = stringResource(Res.string.endorsing_lets_the_confederation_sign), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Button( + modifier = Modifier.fillMaxWidth(), + enabled = !current.isActing, + onClick = { viewModel.endorse(onSuccess = toSession, onFailure = { notify(couldNotAnswer) }) }, + ) { Text(stringResource(Res.string.endorse)) } + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = reasonField, + label = { Text(stringResource(Res.string.reason_optional)) }, + lineLimits = TextFieldLineLimits.SingleLine, + ) + OutlinedButton( + modifier = Modifier.fillMaxWidth(), + enabled = !current.isActing, + onClick = { viewModel.objectTo(reasonField.text.toString(), onSuccess = toSession, onFailure = { notify(couldNotAnswer) }) }, + ) { Text(stringResource(Res.string.object_to_the_change)) } + } + + if (current.canWithdraw && identityCanSign) { + HorizontalDivider() + OutlinedButton( + modifier = Modifier.fillMaxWidth(), + enabled = !current.isActing, + onClick = { viewModel.objectTo("", onSuccess = toSession, onFailure = { notify(couldNotAnswer) }) }, + ) { Text(stringResource(Res.string.withdraw_the_change)) } + } + } + } + } + } +} + +@Composable +private fun fieldLabel(field: FieldName): String = stringResource( + when (field) { + FieldName.NAME -> Res.string.name + FieldName.ABOUT -> Res.string.about + FieldName.PICTURE -> Res.string.picture_url + FieldName.WEBSITE -> Res.string.website + FieldName.NIP05 -> Res.string.nostr_address + } +) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationScreen.kt new file mode 100644 index 00000000..3ba909ac --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationScreen.kt @@ -0,0 +1,328 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ChevronRight +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.Groups +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +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.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +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.core.hexToByteArray +import mobi.giza.compose.extensions.toFormattedTimeAndDateString +import mobi.giza.compose.extensions.toNpub +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.repository.ProfileChangeProblem +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.change_declined +import mobi.giza.compose.resources.change_endorsed +import mobi.giza.compose.resources.change_expired +import mobi.giza.compose.resources.change_open +import mobi.giza.compose.resources.change_published +import mobi.giza.compose.resources.change_superseded +import mobi.giza.compose.resources.change_withdrawn +import mobi.giza.compose.resources.confederation_groups +import mobi.giza.compose.resources.confederation_groups_to_act +import mobi.giza.compose.resources.confederation_has_no_profile_yet +import mobi.giza.compose.resources.confederation_profile +import mobi.giza.compose.resources.confederation_proposed_by +import mobi.giza.compose.resources.edit_the_confederations_profile +import mobi.giza.compose.resources.how_it_was_formed +import mobi.giza.compose.resources.n_admins_hold_its_key +import mobi.giza.compose.resources.n_of_m_endorsements +import mobi.giza.compose.resources.no_name_on_this_profile +import mobi.giza.compose.resources.no_profile_changes_yet +import mobi.giza.compose.resources.only_admins_see_profile_changes +import mobi.giza.compose.resources.open_the_confederations_room +import mobi.giza.compose.resources.open_the_signing_session +import mobi.giza.compose.resources.profile_changes +import mobi.giza.compose.resources.profile_problem_cannot_sign +import mobi.giza.compose.resources.profile_problem_group_without_inbox +import mobi.giza.compose.resources.profile_problem_no_inbox +import mobi.giza.compose.resources.profile_problem_no_record +import mobi.giza.compose.resources.profile_problem_not_admin +import mobi.giza.compose.resources.profile_problem_not_member +import mobi.giza.compose.resources.this_device_knows_nothing_of_that_confederation +import mobi.giza.compose.resources.waiting_for_the_group_to_sign_its_answer +import mobi.giza.compose.ui.composable.navigation.routes.ChatRoomMessagingRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProfileChangeRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProposalRoute +import mobi.giza.compose.ui.composable.navigation.routes.EditConfederationProfileRoute +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.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.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.ConfederationViewModel +import mobi.giza.compose.ui.view.state.ConfederationUIState +import org.jetbrains.compose.resources.stringResource + +/** + * A formed confederation, seen from one of its member groups (docs/confederation-profile.md, D1): + * its profile, the groups it is made of, and the changes to its profile, with the way to propose one. + * + * Every member of a member group can open it. Members who are not admins hold none of the groups' + * statements, so for them it shows what is public -- the charter's groups and the signed profile -- + * and says why the changes are missing rather than showing none. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ConfederationScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + confederationId: HexKey, + initialConfederationUIState: ConfederationUIState = ConfederationUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: ConfederationViewModel = viewModel( + factory = ConfederationViewModel.factory( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + confederationId = confederationId, + initialConfederationUIState = initialConfederationUIState, + chatRepository = chatRepository, + confederationRepository = confederationRepository, + ) + ) + LaunchedEffect(true) { + if (initialConfederationUIState == ConfederationUIState.Loading) viewModel.initiate() + } + val state by viewModel.uiState.collectAsState() + val identityCanSign = LocalCanSign.current + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(text = (state as? ConfederationUIState.Loaded)?.name ?: "", maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + ) { padding -> + ScreenStateTransition(state) { uiState -> + when (val current = uiState) { + is ConfederationUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = current.message, onRetry = null) + + ConfederationUIState.Loading -> LoadingDataIndicator(modifier = Modifier.padding(padding)) + + ConfederationUIState.NotHeld -> EmptyState( + modifier = Modifier.padding(padding), + message = stringResource(Res.string.this_device_knows_nothing_of_that_confederation), + ) + + is ConfederationUIState.Loaded -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + // The profile, as the confederation signed it. + Text(text = stringResource(Res.string.confederation_profile), style = MaterialTheme.typography.titleSmall) + ConfederationProfileCard(current) + + current.pendingSessionId?.let { sessionId -> + Text(text = stringResource(Res.string.waiting_for_the_group_to_sign_its_answer)) + TextButton(onClick = { onNavigateToRoute(FrostSigningRoute(activeUserPublicKey, chatRoomId, sessionId)) }) { + Text(stringResource(Res.string.open_the_signing_session)) + } + } + if (current.readsChanges) { + Button( + modifier = Modifier.fillMaxWidth(), + enabled = current.canEdit && identityCanSign, + onClick = { onNavigateToRoute(EditConfederationProfileRoute(activeUserPublicKey, chatRoomId, confederationId)) }, + ) { + Icon(Icons.Default.Edit, contentDescription = Decorative) + Text(text = stringResource(Res.string.edit_the_confederations_profile), modifier = Modifier.padding(start = MaterialTheme.spacing.relatedGap)) + } + current.problem?.let { problem -> + Text( + text = problemText(problem), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + // The groups it is made of. + HorizontalDivider() + Text(text = stringResource(Res.string.confederation_groups), style = MaterialTheme.typography.titleSmall) + Text( + text = stringResource(Res.string.confederation_groups_to_act, current.threshold, current.groups.size), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + current.groups.forEach { group -> + ListItem( + leadingContent = { Icon(Icons.Default.Groups, contentDescription = Decorative) }, + headlineContent = { Text(text = group.name, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = if (group.roleHolders.isEmpty()) null else { + { + Column { + Text(stringResource(Res.string.n_admins_hold_its_key, group.roleHolders.size)) + Text( + text = group.roleHolders.joinToString(", "), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } + }, + ) + } + + // The changes to its profile: only the groups' admins hold them. + HorizontalDivider() + Text(text = stringResource(Res.string.profile_changes), style = MaterialTheme.typography.titleSmall) + when { + !current.readsChanges -> EmptyState(message = stringResource(Res.string.only_admins_see_profile_changes)) + current.changes.isEmpty() -> EmptyState(message = stringResource(Res.string.no_profile_changes_yet)) + else -> current.changes.forEach { change -> + ProfileChangeCard( + status = change, + proposer = current.names[change.change.proposingGroup] ?: change.change.proposingGroup.take(12), + onClick = { onNavigateToRoute(ConfederationProfileChangeRoute(activeUserPublicKey, chatRoomId, change.change.id)) }, + ) + } + } + + HorizontalDivider() + if (current.holdsRoom) { + TextButton(onClick = { onNavigateToRoute(ChatRoomMessagingRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = confederationId, relayHint = null)) }) { + Text(stringResource(Res.string.open_the_confederations_room)) + } + } + current.formingProposalId?.let { proposalId -> + TextButton(onClick = { onNavigateToRoute(ConfederationProposalRoute(activeUserPublicKey, chatRoomId, proposalId)) }) { + Text(stringResource(Res.string.how_it_was_formed)) + } + } + } + } + } + } +} + +@Composable +private fun ConfederationProfileCard(state: ConfederationUIState.Loaded) { + val profile = state.profile + Card(modifier = Modifier.fillMaxWidth()) { + ListItem( + leadingContent = { ProfileAvatar(publicKey = state.confederationId, picture = profile?.picture(), name = profile?.name() ?: state.name) }, + headlineContent = { + Text( + text = profile?.let { it.name() ?: stringResource(Res.string.no_name_on_this_profile) } ?: state.name, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + }, + supportingContent = { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + if (profile == null) { + Text(stringResource(Res.string.confederation_has_no_profile_yet)) + } else { + profile.nip05()?.let { Text(text = it, style = MaterialTheme.typography.labelMedium, maxLines = 1, overflow = TextOverflow.Ellipsis) } + profile.about()?.let { Text(text = it, maxLines = 3, overflow = TextOverflow.Ellipsis) } + profile.website()?.let { Text(text = it, style = MaterialTheme.typography.labelMedium, maxLines = 1, overflow = TextOverflow.Ellipsis) } + } + Text( + text = state.confederationId.hexToByteArray().toNpub(), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + }, + ) + } +} + +@Composable +private fun ProfileChangeCard(status: ConfederationProfileChangeStatus, proposer: String, onClick: () -> Unit) { + val name = mobi.giza.compose.managers.ConfederationProfileRefusal.metadataOf(status.change.profile)?.anyName()?.takeIf { it.isNotBlank() } + Card(modifier = Modifier.fillMaxWidth(), onClick = onClick) { + ListItem( + headlineContent = { Text(text = name ?: stringResource(Res.string.no_name_on_this_profile), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + overlineContent = { Text(changeStateLabel(status.state)) }, + supportingContent = { + Column { + Text(stringResource(Res.string.confederation_proposed_by, proposer)) + Text( + text = stringResource(Res.string.n_of_m_endorsements, status.endorsers.size, status.change.threshold), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + text = kotlin.time.Instant.fromEpochSeconds(status.change.createdAt).toFormattedTimeAndDateString(), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + }, + trailingContent = { Icon(Icons.Default.ChevronRight, contentDescription = Decorative) }, + ) + } +} + +@Composable +internal fun changeStateLabel(state: ConfederationProfileChangeState): String = stringResource( + when (state) { + ConfederationProfileChangeState.OPEN -> Res.string.change_open + ConfederationProfileChangeState.ENDORSED -> Res.string.change_endorsed + ConfederationProfileChangeState.PUBLISHED -> Res.string.change_published + ConfederationProfileChangeState.SUPERSEDED -> Res.string.change_superseded + ConfederationProfileChangeState.DECLINED -> Res.string.change_declined + ConfederationProfileChangeState.WITHDRAWN -> Res.string.change_withdrawn + ConfederationProfileChangeState.EXPIRED -> Res.string.change_expired + } +) + +@Composable +internal fun problemText(problem: ProfileChangeProblem): String = when (problem) { + ProfileChangeProblem.NoRecord -> stringResource(Res.string.profile_problem_no_record) + ProfileChangeProblem.NotMember -> stringResource(Res.string.profile_problem_not_member) + ProfileChangeProblem.CannotSign -> stringResource(Res.string.profile_problem_cannot_sign) + ProfileChangeProblem.NotAdmin -> stringResource(Res.string.profile_problem_not_admin) + ProfileChangeProblem.NoInbox -> stringResource(Res.string.profile_problem_no_inbox) + is ProfileChangeProblem.GroupWithoutInbox -> stringResource(Res.string.profile_problem_group_without_inbox, problem.name) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt index 29b663cb..0849d14d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt @@ -45,6 +45,7 @@ import mobi.giza.compose.resources.confederations import mobi.giza.compose.resources.propose_a_confederation import mobi.giza.compose.resources.this_device_holds_no_confederation_proposals_for_this_group import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProposalRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRoute import mobi.giza.compose.ui.composable.navigation.routes.ProposeConfederationRoute import mobi.giza.compose.ui.composable.navigation.routes.Route import mobi.giza.compose.ui.composable.widgets.Decorative @@ -147,8 +148,16 @@ fun ConfederationsScreen( ConfederationProposalCard( item = item, onClick = { + // A formed confederation opens itself rather than the vote that + // made it: docs/confederation-profile.md, D1. onNavigateToRoute( - ConfederationProposalRoute( + item.confederationId?.let { confederationId -> + ConfederationRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + confederationId = confederationId, + ) + } ?: ConfederationProposalRoute( activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, proposalId = item.status.proposal.id, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditConfederationProfileScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditConfederationProfileScreen.kt new file mode 100644 index 00000000..ea93f1ac --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditConfederationProfileScreen.kt @@ -0,0 +1,183 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Draw +import androidx.compose.material3.BottomAppBar +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.a_change_goes_to_every_group +import mobi.giza.compose.resources.could_not_propose_the_change +import mobi.giza.compose.resources.edit_confederation_profile +import mobi.giza.compose.resources.propose_from +import mobi.giza.compose.resources.propose_to_the_groups +import mobi.giza.compose.resources.this_device_knows_nothing_of_that_confederation +import mobi.giza.compose.resources.what_the_confederation_says_about_itself +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.Decorative +import mobi.giza.compose.ui.composable.widgets.EmptyState +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.NostrProfileFields +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.composable.widgets.buttons.ExtendedFab +import mobi.giza.compose.ui.composable.widgets.rememberNostrProfileFieldStates +import mobi.giza.compose.ui.composable.widgets.rememberNotifier +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.EditConfederationProfileViewModel +import mobi.giza.compose.ui.view.state.EditConfederationProfileUIState +import org.jetbrains.compose.resources.stringResource + +/** + * The form for a change to a confederation's profile (docs/confederation-profile.md, D2): the same + * fields as a group's, seeded from the confederation's newest profile. Pressing the button asks a + * group -- the member's own, or one they pick when they are an admin of more than one -- to propose + * it, sealed to every other group's inbox. Nothing about the profile has changed when this closes: + * it changes once enough groups have endorsed it and the confederation has signed it. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun EditConfederationProfileScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + confederationId: HexKey, + initialUIState: EditConfederationProfileUIState = EditConfederationProfileUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: EditConfederationProfileViewModel = viewModel( + factory = EditConfederationProfileViewModel.factory( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + confederationId = confederationId, + initialUIState = initialUIState, + chatRepository = chatRepository, + confederationRepository = confederationRepository, + ) + ) + LaunchedEffect(true) { + if (initialUIState == EditConfederationProfileUIState.Loading) viewModel.initiate() + } + + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotPropose = stringResource(Res.string.could_not_propose_the_change) + val identityCanSign = LocalCanSign.current + val state by viewModel.uiState.collectAsState() + + ScreenStateTransition(state) { uiState -> + when (val current = uiState) { + EditConfederationProfileUIState.Loading -> LoadingDataIndicator() + + EditConfederationProfileUIState.NotHeld -> EmptyState(message = stringResource(Res.string.this_device_knows_nothing_of_that_confederation)) + + is EditConfederationProfileUIState.Loaded -> { + val fields = rememberNostrProfileFieldStates(current.profile) + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + modifier = Modifier.imePadding(), + topBar = { + TopAppBar( + title = { Text(text = stringResource(Res.string.edit_confederation_profile), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + bottomBar = { + BottomAppBar( + actions = {}, + floatingActionButton = { + ExtendedFab( + label = stringResource(Res.string.propose_to_the_groups), + icon = { Icon(Icons.Default.Draw, contentDescription = Decorative) }, + enabled = current.selectedGroup != null && !current.isActing && identityCanSign, + onClick = { + viewModel.propose( + fields = fields, + // Onto the group's signing session: the profile changes only + // once enough groups endorse it, so going back to the + // confederation would read as a failure. + onSuccess = { groupId, sessionId -> + onNavigateToRouteAndPopUpInclusive( + FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = groupId, sessionId = sessionId) + ) + }, + onFailure = { reason -> notify(reason ?: couldNotPropose) }, + ) + }, + ) + }, + ) + }, + ) { innerPadding -> + Column( + modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + Text(text = current.name, style = MaterialTheme.typography.headlineSmall) + Text(stringResource(Res.string.what_the_confederation_says_about_itself)) + Text( + text = stringResource(Res.string.a_change_goes_to_every_group, current.threshold, current.groupCount), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + current.problem?.let { problem -> + Text(text = problemText(problem), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) + } + + // Only an admin of more than one member group has a choice to make. + if (current.proposingGroups.size > 1) { + Text(text = stringResource(Res.string.propose_from), style = MaterialTheme.typography.titleSmall) + current.proposingGroups.forEach { group -> + ListItem( + modifier = Modifier.selectable( + selected = group == current.selectedGroup, + role = Role.RadioButton, + onClick = { viewModel.select(group) }, + ), + leadingContent = { RadioButton(selected = group == current.selectedGroup, onClick = null) }, + headlineContent = { Text(text = current.names[group] ?: group.take(12), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + ) + } + } + + NostrProfileFields(fields) + } + } + } + } + } +} 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 index d59a79c1..182ccf28 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt @@ -1,6 +1,5 @@ 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 @@ -10,25 +9,14 @@ 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 @@ -39,8 +27,6 @@ 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 @@ -55,6 +41,8 @@ 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.NostrProfileFields +import mobi.giza.compose.ui.composable.widgets.rememberNostrProfileFieldStates 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 @@ -66,21 +54,11 @@ 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 @@ -147,13 +125,8 @@ fun EditGroupNostrProfileScreen( 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() ?: "") + // an edit of it, and saved as typed, so a rotation keeps the edits. + val fields = rememberNostrProfileFieldStates(profile) // 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. @@ -186,11 +159,11 @@ fun EditGroupNostrProfileScreen( localChatRoom = editGroupNostrProfileUIState.localChatRoom, groupNostrProfile = profile, - nameField = nameFieldState, - aboutField = aboutFieldState, - pictureField = pictureFieldState, - websiteField = websiteFieldState, - nip05Field = nip05FieldState, + nameField = fields.name, + aboutField = fields.about, + pictureField = fields.picture, + websiteField = fields.website, + nip05Field = fields.nip05, onSuccess = { sessionId -> // Onto the session rather than back // to the group. The profile has not @@ -253,50 +226,7 @@ fun EditGroupNostrProfileScreen( ) } - 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) - ) + NostrProfileFields(fields) } } } @@ -328,43 +258,6 @@ fun EditGroupNostrProfileScreen( } } -/** - * 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() { 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 0e226c81..520104df 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 @@ -7,6 +7,12 @@ import mobi.giza.compose.ui.composable.BroadcastGroupSignedEventScreen import mobi.giza.compose.ui.composable.navigation.routes.AddGroupPostRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationsRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProposalRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRoute +import mobi.giza.compose.ui.composable.navigation.routes.EditConfederationProfileRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProfileChangeRoute +import mobi.giza.compose.ui.composable.ConfederationScreen +import mobi.giza.compose.ui.composable.EditConfederationProfileScreen +import mobi.giza.compose.ui.composable.ConfederationProfileChangeScreen import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRitualRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute import mobi.giza.compose.ui.composable.ConfederationSigningScreen @@ -1348,6 +1354,51 @@ fun GizaNavHost( onNavigateBack = { navController.popBackStack() } ) } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + ConfederationScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + confederationId = route.confederationId, + chatRepository = databaseChatRepository, + confederationRepository = databaseConfederationRepository, + onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, + onNavigateBack = { navController.popBackStack() } + ) + } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + EditConfederationProfileScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + confederationId = route.confederationId, + chatRepository = databaseChatRepository, + confederationRepository = databaseConfederationRepository, + onNavigateToRouteAndPopUpInclusive = { signingRoute -> + // Replace the form so back returns to the confederation rather than to + // an edit whose proposal has already gone to the group. + navController.navigate(route = signingRoute) { + popUpTo { inclusive = true } + } + }, + onNavigateBack = { navController.popBackStack() } + ) + } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + ConfederationProfileChangeScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + changeId = route.changeId, + chatRepository = databaseChatRepository, + confederationRepository = databaseConfederationRepository, + onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, + onNavigateBack = { navController.popBackStack() } + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationRoute.kt new file mode 100644 index 00000000..38e6766e --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationRoute.kt @@ -0,0 +1,31 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** + * A formed confederation, seen from one of its member groups: its profile, its groups and the + * changes to its profile (docs/confederation-profile.md, D1). [chatRoomId] is the group's room it + * was opened from, which is the group a change made here is proposed from. + */ +@Serializable +data class ConfederationRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val confederationId: String, +): Route() + +/** The form for a change to a confederation's profile, proposed by one of its groups (D2). */ +@Serializable +data class EditConfederationProfileRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val confederationId: String, +): Route() + +/** One proposed change to a confederation's profile, and this group's answer to it (D3). */ +@Serializable +data class ConfederationProfileChangeRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val changeId: String, +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/NostrProfileFields.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/NostrProfileFields.kt new file mode 100644 index 00000000..7366fa33 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/NostrProfileFields.kt @@ -0,0 +1,137 @@ +package mobi.giza.compose.ui.composable.widgets + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.foundation.text.input.rememberTextFieldState +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.Image +import androidx.compose.material.icons.filled.Link +import androidx.compose.material.icons.filled.Title +import androidx.compose.material3.BottomAppBarDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.about +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.website +import org.jetbrains.compose.resources.stringResource + +/** + * The five fields of a nostr profile a group or a confederation edits here: what the group's form + * and the confederation's share (docs/confederation-profile.md, D2), so they cannot drift apart. + * + * Seeded from the profile already signed, so the form is an edit of it, and saved as typed, so a + * rotation keeps the edits. [template] turns them into the kind:0 to sign, built on the newest + * profile so a field this form does not offer is carried across (`GroupNostrProfile.template`). + */ +class NostrProfileFieldStates( + val name: TextFieldState, + val about: TextFieldState, + val picture: TextFieldState, + val website: TextFieldState, + val nip05: TextFieldState, +) { + fun template(latest: GroupNostrProfile?): EventTemplate = GroupNostrProfile.template( + latest = latest, + name = name.text.toString().trim(), + about = about.text.toString().trim(), + picture = picture.text.toString().trim(), + website = website.text.toString().trim(), + nip05 = nip05.text.toString().trim(), + ) +} + +@Composable +fun rememberNostrProfileFieldStates(profile: GroupNostrProfile?): NostrProfileFieldStates = NostrProfileFieldStates( + name = rememberTextFieldState(profile?.name() ?: ""), + about = rememberTextFieldState(profile?.about() ?: ""), + picture = rememberTextFieldState(profile?.picture() ?: ""), + website = rememberTextFieldState(profile?.website() ?: ""), + nip05 = rememberTextFieldState(profile?.nip05() ?: ""), +) + +/** The five fields, in the order a profile reads. Each icon sits beside its label, so it is decorative. */ +@Composable +fun NostrProfileFields(states: NostrProfileFieldStates) { + NostrProfileField( + state = states.name, + icon = Icons.Default.Title, + label = stringResource(Res.string.name), + placeholder = stringResource(Res.string.eg_translation_collective), + ) + NostrProfileField( + state = states.about, + icon = Icons.AutoMirrored.Filled.Notes, + 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 = states.picture, + icon = Icons.Default.Image, + label = stringResource(Res.string.picture_url), + placeholder = stringResource(Res.string.eg_https_example_com_group_png), + ) + NostrProfileField( + state = states.website, + icon = Icons.Default.Link, + label = stringResource(Res.string.website), + placeholder = stringResource(Res.string.eg_https_example_com), + ) + NostrProfileField( + state = states.nip05, + icon = Icons.Default.AlternateEmail, + label = stringResource(Res.string.nostr_address), + placeholder = stringResource(Res.string.eg_group_example_com), + ) +} + +/** + * One field of the profile, in the shape the app's other forms use: 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, + 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 = Decorative) }, + label = { Text(text = label) }, + placeholder = { Text(text = placeholder) }, + ) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt index 63e076d7..7fbf73e7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt @@ -126,6 +126,10 @@ fun ChatTranscript( onOpenSigning: (sessionId: String?) -> Unit, /** Opens a confederation's request to sign: docs/confederation.md, Phase 15. */ onOpenConfederationSigning: (attemptId: String) -> Unit = {}, + /** Opens a change to a confederation's profile: docs/confederation-profile.md, D8. */ + onOpenConfederationProfileChange: (changeId: String) -> Unit = {}, + /** Opens a confederation, from the line saying it has a new profile. */ + onOpenConfederation: (confederationId: String) -> Unit = {}, /** Opens the room's proposals, all of them, whatever their state. */ onOpenProposals: () -> Unit, ) { @@ -393,6 +397,28 @@ fun ChatTranscript( return@items } + // A change to a confederation's profile, or the profile it ended in: + // each opens what it is about. docs/confederation-profile.md, D8. + if (localChatMessage.chatMessage.messageType in ChatMessage.CONFEDERATION_PROFILE_TYPES) { + val target = localChatMessage.chatMessage.frostSigningSessionId + RitualNotice( + localChatMessage = localChatMessage, + isAnswered = true, + isSettled = true, + onClick = target?.let { + { + if (localChatMessage.chatMessage.messageType == ChatMessage.TYPE_CONFEDERATION_PROFILE_PUBLISHED) { + onOpenConfederation(it) + } else { + onOpenConfederationProfileChange(it) + } + } + }, + opens = null, + ) + return@items + } + if (localChatMessage.chatMessage.messageType in ChatMessage.GROUP_IDENTITY_TYPES) { RitualNotice( localChatMessage = localChatMessage, 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 f71ca546..be1b2433 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 @@ -135,6 +135,7 @@ class ChatRoomDetailViewModel( confederationProposalCount = chatRepository.confederationProposalCount(chatRoomId), inbox = chatRepository.inboxSummary(localChatRoom), confederationName = chatRepository.confederationOfRoom(chatRoomId), + memberConfederations = if (ExperimentalFeatures.confederation) chatRepository.memberConfederations(chatRoomId) else emptyList(), groupDmRow = runCatching { chatRepository.groupDmRow(chatRoomId, localChatRoom.chatRoom.userPublicKey) } .onFailure { if (it is CancellationException) throw it else logger.w(throwable = it) { "Couldn't read $chatRoomId's messages row" } } .getOrNull(), diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProfileChangeViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProfileChangeViewModel.kt new file mode 100644 index 00000000..41693e6a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProfileChangeViewModel.kt @@ -0,0 +1,132 @@ +package mobi.giza.compose.ui.view.model + +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 com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.managers.ConfederationProfileRefusal +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState +import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState.Field +import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState.FieldName + +/** + * One change to a confederation's profile from one of its groups, and the group's answer to it + * (docs/confederation-profile.md, D3). Answering is a group signature, so each button opens a + * signing session and the screen goes to it; one answer at a time. + */ +class ConfederationProfileChangeViewModel( + val activeUserPublicKey: HexKey, + val chatRoomId: String, + val changeId: HexKey, + initialUIState: ConfederationProfileChangeUIState, + val chatRepository: ChatRepository, + val confederationRepository: ConfederationRepository, +) : ViewModel() { + private val logger = Logger.withTag(TAG) + private val state = MutableStateFlow(initialUIState) + val uiState: StateFlow = state.asStateFlow() + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) ?: run { + state.value = ConfederationProfileChangeUIState.Error("Couldn't find the group") + return@launch + } + val canAnswer = GroupStatementCapability.roomIsOpen(localChatRoom) && chatRepository.canSign(chatRoomId) && + confederationRepository.isAdmin(chatRoomId, activeUserPublicKey) && + confederationRepository.holdsAnnouncedInbox(chatRoomId, activeUserPublicKey) + val base = confederationRepository.profileBaseOf(changeId) + + combine( + confederationRepository.observeProfileChange(changeId), + confederationRepository.observePendingProfileAnswer(chatRoomId, changeId), + ) { status, pending -> status to pending }.collect { (status, pending) -> + if (status == null) { + state.value = ConfederationProfileChangeUIState.NotHeld + return@collect + } + val acting = (state.value as? ConfederationProfileChangeUIState.Loaded)?.isActing == true + state.value = ConfederationProfileChangeUIState.Loaded( + localChatRoom = localChatRoom, + status = status, + confederationName = confederationRepository.membership(status.change.confederation)?.name ?: "", + differences = differences(base, ConfederationProfileRefusal.metadataOf(status.change.profile)), + names = status.change.groups.associateWith { confederationRepository.nameOf(it, chatRoomId) }, + canAnswer = canAnswer, + pendingSessionId = pending?.id, + isActing = acting, + ) + } + } + } + + fun endorse(onSuccess: (String) -> Unit, onFailure: () -> Unit) = act(onSuccess, onFailure) { loaded -> + confederationRepository.proposeProfileEndorsement(loaded.localChatRoom, activeUserPublicKey, changeId) + } + + /** An objection, with [reason]; from the group that proposed the change, its withdrawal. */ + fun objectTo(reason: String, onSuccess: (String) -> Unit, onFailure: () -> Unit) = act(onSuccess, onFailure) { loaded -> + confederationRepository.proposeProfileObjection(loaded.localChatRoom, activeUserPublicKey, changeId, reason.trim()) + } + + private fun act( + onSuccess: (String) -> Unit, + onFailure: () -> Unit, + propose: suspend (ConfederationProfileChangeUIState.Loaded) -> FrostSigningSession, + ) { + val loaded = state.value as? ConfederationProfileChangeUIState.Loaded ?: return + if (loaded.isActing) return + state.update { (it as? ConfederationProfileChangeUIState.Loaded)?.copy(isActing = true) ?: it } + viewModelScope.launch(Dispatchers.IO) { + val session = runCatching { propose(loaded) } + .onFailure { logger.e("Could not ask $chatRoomId to answer $changeId", it) } + .getOrNull() + state.update { (it as? ConfederationProfileChangeUIState.Loaded)?.copy(isActing = false) ?: it } + viewModelScope.launch(Dispatchers.Main) { if (session != null) onSuccess(session.id) else onFailure() } + } + } + + companion object { + private const val TAG = "ConfederationProfileChangeViewModel" + + /** The fields a person edits that differ between [before] and [after]. */ + fun differences(before: UserMetadata?, after: UserMetadata?): List { + fun String?.clean() = this?.takeIf { it.isNotBlank() } + return listOf( + Field(FieldName.NAME, before?.anyName().clean(), after?.anyName().clean()), + Field(FieldName.ABOUT, before?.about.clean(), after?.about.clean()), + Field(FieldName.PICTURE, before?.picture.clean(), after?.picture.clean()), + Field(FieldName.WEBSITE, before?.website.clean(), after?.website.clean()), + Field(FieldName.NIP05, before?.nip05.clean(), after?.nip05.clean()), + ).filter { it.before != it.after } + } + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + changeId: HexKey, + initialUIState: ConfederationProfileChangeUIState = ConfederationProfileChangeUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + ConfederationProfileChangeViewModel(activeUserPublicKey, chatRoomId, changeId, initialUIState, chatRepository, confederationRepository) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationViewModel.kt new file mode 100644 index 00000000..96ff91c4 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationViewModel.kt @@ -0,0 +1,96 @@ +package mobi.giza.compose.ui.view.model + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.launch +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.ui.view.state.ConfederationUIState + +/** + * A formed confederation from one of its member groups (docs/confederation-profile.md, D1): its + * profile, its groups, and the changes to its profile. Watched, since a change, an answer and a newly + * signed profile all arrive while the screen is open. + */ +class ConfederationViewModel( + val activeUserPublicKey: HexKey, + val chatRoomId: String, + val confederationId: HexKey, + initialConfederationUIState: ConfederationUIState, + val chatRepository: ChatRepository, + val confederationRepository: ConfederationRepository, +) : ViewModel() { + private val state = MutableStateFlow(initialConfederationUIState) + val uiState: StateFlow = state.asStateFlow() + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) ?: run { + state.value = ConfederationUIState.Error("Couldn't find the group") + return@launch + } + val membership = confederationRepository.membership(confederationId) ?: run { + state.value = ConfederationUIState.NotHeld + return@launch + } + val holders = confederationRepository.roleHolders(confederationId) + val names = membership.groups.associateWith { confederationRepository.nameOf(it, chatRoomId) } + val groups = membership.groups.map { group -> + ConfederationUIState.Group(group, names.getValue(group), holders[group].orEmpty().map { confederationRepository.nameOf(it) }) + } + val readsChanges = confederationRepository.isAdmin(chatRoomId, activeUserPublicKey) + val problem = confederationRepository.profileChangeProblem(chatRoomId, activeUserPublicKey, confederationId) + val formingProposalId = confederationRepository.formingProposalOf(confederationId) + val holdsRoom = confederationRepository.holdsRoomOf(confederationId) + + combine( + confederationRepository.observeProfile(confederationId), + confederationRepository.observeProfileChanges(confederationId), + confederationRepository.observePendingProfileChange(chatRoomId, confederationId), + ) { profile, changes, pending -> Triple(profile, changes, pending) }.collect { (profile, changes, pending) -> + state.value = ConfederationUIState.Loaded( + localChatRoom = localChatRoom, + confederationId = confederationId, + name = membership.name, + threshold = membership.threshold, + groups = groups, + profile = profile, + changes = changes, + readsChanges = readsChanges, + problem = problem, + pendingSessionId = pending?.id, + formingProposalId = formingProposalId, + holdsRoom = holdsRoom, + names = names, + ) + } + } + } + + companion object { + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + confederationId: HexKey, + initialConfederationUIState: ConfederationUIState = ConfederationUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + ConfederationViewModel( + activeUserPublicKey, chatRoomId, confederationId, initialConfederationUIState, chatRepository, confederationRepository, + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationsViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationsViewModel.kt index 14c00b2b..a1971c14 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationsViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationsViewModel.kt @@ -48,7 +48,7 @@ class ConfederationsViewModel( combine( confederationRepository.observeStatusesNaming(chatRoomId), confederationRepository.observeConfederationsOf(chatRoomId), - ) { statuses, formed -> statuses to formed.map { it.proposalId }.toSet() }.collect { (statuses, formed) -> + ) { statuses, formed -> statuses to formed.associate { it.proposalId to it.id } }.collect { (statuses, formed) -> confederationsUIState = ConfederationsUIState.Loaded( localChatRoom = localChatRoom, proposals = statuses.map { status -> @@ -56,6 +56,7 @@ class ConfederationsViewModel( status = status, proposerName = confederationRepository.nameOf(status.proposal.proposingGroup, chatRoomId), formed = status.proposal.id in formed, + confederationId = formed[status.proposal.id], ) }, canPropose = canPropose, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditConfederationProfileViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditConfederationProfileViewModel.kt new file mode 100644 index 00000000..c22f972a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditConfederationProfileViewModel.kt @@ -0,0 +1,105 @@ +package mobi.giza.compose.ui.view.model + +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 com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.ui.composable.widgets.NostrProfileFieldStates +import mobi.giza.compose.ui.view.state.EditConfederationProfileUIState + +/** + * The form for a change to a confederation's profile (docs/confederation-profile.md, D2). Pressing + * the button proposes rather than saves: the group chosen signs a statement proposing the change, + * sealed to every other member group's inbox, and the screen hands over to that signing session. + */ +class EditConfederationProfileViewModel( + val activeUserPublicKey: HexKey, + val chatRoomId: String, + val confederationId: HexKey, + initialUIState: EditConfederationProfileUIState, + val chatRepository: ChatRepository, + val confederationRepository: ConfederationRepository, +) : ViewModel() { + private val logger = Logger.withTag(TAG) + private val state = MutableStateFlow(initialUIState) + val uiState: StateFlow = state.asStateFlow() + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val membership = confederationRepository.membership(confederationId) ?: run { + state.value = EditConfederationProfileUIState.NotHeld + return@launch + } + val groups = confederationRepository.proposingGroupsFor(activeUserPublicKey, confederationId) + .sortedBy { if (it == chatRoomId) 0 else 1 } + state.value = EditConfederationProfileUIState.Loaded( + confederationId = confederationId, + name = membership.name, + threshold = membership.threshold, + groupCount = membership.groups.size, + profile = confederationRepository.observeProfile(confederationId).first(), + proposingGroups = groups, + names = membership.groups.associateWith { confederationRepository.nameOf(it) }, + problem = if (groups.isEmpty()) confederationRepository.profileChangeProblem(chatRoomId, activeUserPublicKey, confederationId) else null, + selectedGroup = groups.firstOrNull(), + ) + } + } + + fun select(group: HexKey) = state.update { (it as? EditConfederationProfileUIState.Loaded)?.copy(selectedGroup = group) ?: it } + + /** + * Asks the selected group to propose [fields] as the confederation's profile. [onFailure] gets a + * reason a person can read when there is one: a profile too long for every group's seal. + */ + fun propose(fields: NostrProfileFieldStates, onSuccess: (groupId: String, sessionId: String) -> Unit, onFailure: (String?) -> Unit) { + val loaded = state.value as? EditConfederationProfileUIState.Loaded ?: return + val group = loaded.selectedGroup ?: return + if (loaded.isActing) return + state.update { (it as? EditConfederationProfileUIState.Loaded)?.copy(isActing = true) ?: it } + val template = fields.template(loaded.profile) + viewModelScope.launch(Dispatchers.IO) { + val result = runCatching { + val room = chatRepository.getChatRoomByIdentifier(group) ?: throw IllegalStateException("Couldn't find the group") + confederationRepository.proposeProfileChange(room, activeUserPublicKey, confederationId, template.tags, template.content) + }.onFailure { logger.e("Could not propose a profile for $confederationId", it) } + state.update { (it as? EditConfederationProfileUIState.Loaded)?.copy(isActing = false) ?: it } + viewModelScope.launch(Dispatchers.Main) { + result.fold( + onSuccess = { onSuccess(group, it.id) }, + onFailure = { onFailure((it as? IllegalStateException)?.message?.takeIf { message -> message.startsWith("This profile is too long") }) }, + ) + } + } + } + + companion object { + private const val TAG = "EditConfederationProfileViewModel" + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + confederationId: HexKey, + initialUIState: EditConfederationProfileUIState = EditConfederationProfileUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + EditConfederationProfileViewModel(activeUserPublicKey, chatRoomId, confederationId, initialUIState, chatRepository, confederationRepository) + } + } + } +} 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 b833998d..97631c9d 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 @@ -76,6 +76,9 @@ sealed interface ChatRoomDetailUIState { val confederationProposalCount: Int = 0, /** The group's inbox, for its row; null where this device has nothing of it to show. */ val inbox: InboxRowSummary? = null, + /** The formed confederations this group is a member of, as (id, name): each opens its own screen. */ + val memberConfederations: List> = emptyList(), + /** The confederation whose room this is, by name: its membership is fixed until it can sign. */ val confederationName: String? = null, /** What the group's direct messages show here, or nothing. docs/group-threshold-ecdh.md. */ diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProfileChangeUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProfileChangeUIState.kt new file mode 100644 index 00000000..fd3dfad9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProfileChangeUIState.kt @@ -0,0 +1,45 @@ +package mobi.giza.compose.ui.view.state + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus + +/** One change to a confederation's profile, seen from one of its groups (docs/confederation-profile.md, D3). */ +sealed interface ConfederationProfileChangeUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + val status: ConfederationProfileChangeStatus, + val confederationName: String, + /** Each field that would change, as (field, before, after). */ + val differences: List, + val names: Map = emptyMap(), + /** Whether this member can put an answer to the group: an admin with a share and the group's inbox key. */ + val canAnswer: Boolean = false, + /** An answer this group is being asked to sign, not yet signed: one at a time. */ + val pendingSessionId: String? = null, + val isActing: Boolean = false, + ) : ConfederationProfileChangeUIState { + private val roomId get() = localChatRoom.chatRoom.id + private val live get() = status.state == ConfederationProfileChangeState.OPEN || status.state == ConfederationProfileChangeState.ENDORSED + + /** Another group's change this group has not answered, still open. */ + val canEndorseOrObject: Boolean + get() = canAnswer && pendingSessionId == null && live && + status.change.proposingGroup != roomId && !status.hasAnswered(roomId) + + /** This group's own change, not yet published or closed. */ + val canWithdraw: Boolean + get() = canAnswer && pendingSessionId == null && live && status.change.proposingGroup == roomId + } + + enum class FieldName { NAME, ABOUT, PICTURE, WEBSITE, NIP05 } + + data class Field(val name: FieldName, val before: String?, val after: String?) + + data object NotHeld : ConfederationProfileChangeUIState + + data class Error(val message: String) : ConfederationProfileChangeUIState + + data object Loading : ConfederationProfileChangeUIState +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationUIState.kt new file mode 100644 index 00000000..98977442 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationUIState.kt @@ -0,0 +1,46 @@ +package mobi.giza.compose.ui.view.state + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus +import mobi.giza.compose.repository.ProfileChangeProblem + +/** A formed confederation, seen from one of its member groups (docs/confederation-profile.md, D1). */ +sealed interface ConfederationUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + val confederationId: HexKey, + val name: String, + /** How many of [groups] must act for it to sign. */ + val threshold: Int, + val groups: List, + /** The newest profile the confederation has signed that this device holds. */ + val profile: GroupNostrProfile? = null, + /** The changes to its profile this device holds, newest first: an admin's device holds them, nobody else's. */ + val changes: List = emptyList(), + /** Whether this member reads the groups' statements: one of the group's admins. */ + val readsChanges: Boolean = false, + /** Why this member cannot propose a change from this group, or null when they can. */ + val problem: ProfileChangeProblem? = null, + /** A change this group is being asked to propose, not yet signed. */ + val pendingSessionId: String? = null, + /** The proposal the confederation was formed from, where this device holds it. */ + val formingProposalId: HexKey? = null, + /** Whether this device holds the confederation's own room. */ + val holdsRoom: Boolean = false, + /** How to name each group. */ + val names: Map = emptyMap(), + ) : ConfederationUIState { + val canEdit: Boolean get() = problem == null && pendingSessionId == null + } + + /** A member group, with the admins who hold its roles where this device knows them. */ + data class Group(val publicKey: HexKey, val name: String, val roleHolders: List) + + data object NotHeld : ConfederationUIState + + data class Error(val message: String) : ConfederationUIState + + data object Loading : ConfederationUIState +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationsUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationsUIState.kt index c311a154..7c544cef 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationsUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationsUIState.kt @@ -14,7 +14,13 @@ sealed interface ConfederationsUIState { ) : ConfederationsUIState /** One proposal, and how to name the group that made it. */ - data class Item(val status: ConfederationStatus, val proposerName: String, val formed: Boolean = false) + data class Item( + val status: ConfederationStatus, + val proposerName: String, + val formed: Boolean = false, + /** The formed confederation's id, which its card opens. docs/confederation-profile.md, D1. */ + val confederationId: String? = null, + ) data class Error(val message: String) : ConfederationsUIState diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/EditConfederationProfileUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/EditConfederationProfileUIState.kt new file mode 100644 index 00000000..1be68c43 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/EditConfederationProfileUIState.kt @@ -0,0 +1,28 @@ +package mobi.giza.compose.ui.view.state + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.repository.ProfileChangeProblem + +/** The form for a change to a confederation's profile (docs/confederation-profile.md, D2). */ +sealed interface EditConfederationProfileUIState { + data class Loaded( + val confederationId: HexKey, + val name: String, + val threshold: Int, + val groupCount: Int, + /** The profile the change edits: the newest this device holds. */ + val profile: GroupNostrProfile?, + /** The member groups this member can propose from, the one it was opened from first. */ + val proposingGroups: List, + val names: Map, + /** Why the group it was opened from cannot propose, when no group can. */ + val problem: ProfileChangeProblem?, + val selectedGroup: HexKey?, + val isActing: Boolean = false, + ) : EditConfederationProfileUIState + + data object NotHeld : EditConfederationProfileUIState + + data object Loading : EditConfederationProfileUIState +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileScreensJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileScreensJvmTest.kt new file mode 100644 index 00000000..e21d5d90 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileScreensJvmTest.kt @@ -0,0 +1,213 @@ +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.assertCountEquals +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.runDesktopComposeUiTest +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto +import kotlin.test.Test +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.toHex +import mobi.giza.compose.managers.ConfederationStatementFixture +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus +import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.repository.ProfileChangeProblem +import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.view.model.ConfederationProfileChangeViewModel +import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState +import mobi.giza.compose.ui.view.state.ConfederationUIState +import mobi.giza.compose.ui.view.state.EditConfederationProfileUIState + +/** A confederation's screen, its profile form and a change to its profile, as a member meets them (docs/confederation-profile.md, Phase 4). */ +@OptIn(ExperimentalTestApi::class) +class ConfederationProfileScreensJvmTest { + private val agora = ConfederationStatementFixture.npub(1) + private val polis = ConfederationStatementFixture.npub(2) + private val atlasKey = ConfederationStatementFixture.key(9) + private val atlas = ConfederationStatementFixture.npub(atlasKey) + private val now = 1_790_000_000L + + private val localChatRoom = LocalChatRoom( + chatRoom = ChatRoom(id = agora, userPublicKey = "a".repeat(64), subject = "#Agora", description = null, mlsGroupState = "state") + ) + + private val signedProfile: GroupNostrProfile = run { + val content = """{"name":"Atlas","about":"Two groups"}""" + val id = EventHasher.hashId(atlas, now - 100, 0, emptyArray(), content) + val event = Event(id, atlas, now - 100, 0, emptyArray(), content, Nip01Crypto.sign(id.hexToByteArray(), atlasKey.value.toByteArray()).toHex()) + GroupNostrProfile.of(GroupSignedEvent.fromEvent(event, chatRoomId = atlas), atlas)!! + } + + private fun change(by: String, content: String = """{"name":"Atlas of the Coast","about":"Two groups"}""") = + ConfederationProfileStatements.parseChange( + ConfederationProfileStatements.change(by, listOf(if (by == agora) polis else agora), atlas, 2, signedProfile.signedEvent.id, emptyArray(), content, now, now + 1000) + )!! + + private fun status(change: ConfederationProfileStatements.Change) = + ConfederationProfileChangeStatus.of(change, emptyList(), emptyList(), null, published = false, now = now + 1) + + private fun loaded( + readsChanges: Boolean = true, + problem: ProfileChangeProblem? = null, + changes: List = emptyList(), + ) = ConfederationUIState.Loaded( + localChatRoom = localChatRoom, + confederationId = atlas, + name = "Atlas", + threshold = 2, + groups = listOf( + ConfederationUIState.Group(agora, "Agora", listOf("alice", "bob")), + ConfederationUIState.Group(polis, "Polis", emptyList()), + ), + profile = signedProfile, + changes = changes, + readsChanges = readsChanges, + problem = problem, + names = mapOf(agora to "This group", polis to "Polis"), + ) + + // ---- the confederation's screen ---------------------------------------------------------------- + + @Test + fun `an admin sees the profile, the groups with who holds their roles, the changes and the way to edit`() = renderConfederation( + loaded(changes = listOf(status(change(by = polis)))) + ) { + onNodeWithText("Two groups").assertIsDisplayed() + onNodeWithText("Polis").assertIsDisplayed() + onNodeWithText("2 admins hold its key").assertIsDisplayed() + onNodeWithText("alice, bob").assertIsDisplayed() + onNodeWithText("2 of 2 groups to act").assertIsDisplayed() + onNodeWithText("Atlas of the Coast").assertIsDisplayed() + onNodeWithText("Proposed by Polis").assertIsDisplayed() + onNodeWithText("Endorsed by 1 of the 2 groups it needs").assertIsDisplayed() + onNodeWithText("Edit profile").assertIsEnabled() + } + + @Test + fun `a member who is not an admin sees what is public, and why the changes are missing`() = renderConfederation(loaded(readsChanges = false)) { + onNodeWithText("Two groups").assertIsDisplayed() + onNodeWithText("Only the group's admins see proposed changes.").assertIsDisplayed() + onAllNodesWithText("Edit profile").assertCountEquals(0) + } + + @Test + fun `an admin who cannot propose is told why`() = renderConfederation(loaded(problem = ProfileChangeProblem.GroupWithoutInbox("Polis"))) { + onNodeWithText("Polis has no inbox, so it cannot be asked").assertIsDisplayed() + onNodeWithText("Edit profile").assertIsNotEnabled() + } + + // ---- a change ---------------------------------------------------------------------------------- + + private fun changeState(change: ConfederationProfileStatements.Change, pending: String? = null) = ConfederationProfileChangeUIState.Loaded( + localChatRoom = localChatRoom, + status = status(change), + confederationName = "Atlas", + differences = ConfederationProfileChangeViewModel.differences( + signedProfile.metadata, + mobi.giza.compose.managers.ConfederationProfileRefusal.metadataOf(change.profile), + ), + names = mapOf(agora to "This group", polis to "Polis"), + canAnswer = true, + pendingSessionId = pending, + ) + + @Test + fun `another group's change says what it would change, and offers both answers`() = renderChange(changeState(change(by = polis))) { + onNodeWithText("Was: Atlas").assertIsDisplayed() + onNodeWithText("Becomes: Atlas of the Coast").assertIsDisplayed() + onAllNodesWithText("Two groups", substring = true).assertCountEquals(0) + onNodeWithText("Proposed it").assertIsDisplayed() + onNodeWithText("Endorse").assertIsDisplayed() + onNodeWithText("Object").assertIsDisplayed() + onAllNodesWithText("Withdraw the change").assertCountEquals(0) + } + + @Test + fun `this group's own change can be withdrawn, not endorsed`() = renderChange(changeState(change(by = agora))) { + onNodeWithText("Withdraw the change").assertIsDisplayed() + onAllNodesWithText("Endorse").assertCountEquals(0) + } + + @Test + fun `while an answer is being signed, the buttons give way to it`() = renderChange(changeState(change(by = polis), pending = "s".repeat(64))) { + onNodeWithText("Waiting for the group to sign its answer").assertIsDisplayed() + onAllNodesWithText("Endorse").assertCountEquals(0) + } + + // ---- the form ---------------------------------------------------------------------------------- + + private fun form(groups: List) = EditConfederationProfileUIState.Loaded( + confederationId = atlas, name = "Atlas", threshold = 2, groupCount = 2, profile = signedProfile, + proposingGroups = groups, names = mapOf(agora to "Agora", polis to "Polis"), problem = null, selectedGroup = groups.firstOrNull(), + ) + + @Test + fun `the form starts from the signed profile and says who it goes to`() = renderForm(form(listOf(agora))) { + // The heading, and the name field seeded from the profile the confederation signed. + onAllNodesWithText("Atlas").assertCountEquals(2) + onNodeWithText("Two groups").assertIsDisplayed() + onNodeWithText("The confederation signs it once 2 of its 2 groups have endorsed it", substring = true).assertIsDisplayed() + onAllNodesWithText("Propose from").assertCountEquals(0) + onNodeWithText("Propose to the groups").assertIsEnabled() + } + + @Test + fun `an admin of two member groups picks which proposes`() = renderForm(form(listOf(agora, polis))) { + onNodeWithText("Propose from").assertIsDisplayed() + onNodeWithText("Agora").assertIsDisplayed() + onNodeWithText("Polis").assertIsDisplayed() + } + + private fun renderConfederation(state: ConfederationUIState, assertions: ComposeUiTest.() -> Unit) = render(assertions) { + ConfederationScreen( + activeUserPublicKey = "a".repeat(64), chatRoomId = agora, confederationId = atlas, initialConfederationUIState = state, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, confederationRepository = ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY, + onNavigateToRoute = {}, onNavigateBack = {}, + ) + } + + private fun renderChange(state: ConfederationProfileChangeUIState, assertions: ComposeUiTest.() -> Unit) = render(assertions) { + ConfederationProfileChangeScreen( + activeUserPublicKey = "a".repeat(64), chatRoomId = agora, changeId = "c".repeat(64), initialUIState = state, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, confederationRepository = ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY, + onNavigateToRoute = {}, onNavigateBack = {}, + ) + } + + private fun renderForm(state: EditConfederationProfileUIState, assertions: ComposeUiTest.() -> Unit) = render(assertions) { + EditConfederationProfileScreen( + activeUserPublicKey = "a".repeat(64), chatRoomId = agora, confederationId = atlas, initialUIState = state, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, confederationRepository = ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY, + onNavigateToRouteAndPopUpInclusive = {}, onNavigateBack = {}, + ) + } + + private fun render(assertions: ComposeUiTest.() -> Unit, content: @androidx.compose.runtime.Composable () -> Unit) = + runDesktopComposeUiTest(width = 400, height = 3000) { + setContent { + GizaTheme { + ProvideSnackbarHost { + Box(modifier = Modifier.fillMaxSize()) { content() } + } + } + } + assertions() + } +} diff --git a/docs/confederation-profile.md b/docs/confederation-profile.md index 703a12f1..3b0f74b9 100644 --- a/docs/confederation-profile.md +++ b/docs/confederation-profile.md @@ -535,6 +535,18 @@ Tests: `ConfederationProfileScreensJvmTest`, covering each state, the gating of the non-admin view built from the charter and kind:0 alone. `m3Audit` at budget, with no new `.dp` spacing, colour literal or title-case string. +**Built.** `ConfederationProfileScreensJvmTest` 8/8; `m3Audit` at budget; `compileDebugKotlinAndroid` +builds. Where it differs from the above: + +| what the phase said | what it turned out to be | +|---|---| +| `NostrProfileForm` | `widgets/NostrProfileFields.kt`: the five fields and a `NostrProfileFieldStates` holder whose `template` builds the kind:0. Its icons are now `Decorative`, since each sits beside its label; they carried hard-coded English descriptions before | +| the edit screen's own view model | as said; its failure carries the profile-sized reason when there is one, so "too long for 12 groups" reaches the snackbar instead of a generic failure | +| "Signing: waiting for Agora's admins" (D6) | the change's screen names the endorsing groups whose voucher this device has not yet seen. Phase 5 is what makes those vouchers arrive | +| repository methods | on `ConfederationRepository` as interface defaults, so `NO_OP_CONFEDERATION_REPOSITORY` and every fake needed no change; `ProfileChangeProblem` says why a member cannot propose, which the screen and the form turn into words | +| the group detail screen's row | `ChatRepository.memberConfederations`, by record or charter; each row reads "Member of Atlas" and opens the confederation | +| the lines (Phase 3) open the change | `ChatTranscript` gains `onOpenConfederationProfileChange` and `onOpenConfederation`; the published line opens the confederation | + ### Phase 5: from endorsement to signature (D5, D6) - The 30396 voucher message: posted by each role holder's device when its group's 9435 or 9436