From 68a86b4d77d1103b97b4fca1b0caecbfec2a861d Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 16:42:15 +0200 Subject: [PATCH] refactor: remove the unreachable nip30303 document screens (Phase 7, part 1) Nothing navigated to the artifact, chapter, dialect or translation screens: ArtifactDetailRoute, AddArtifactRoute and AddDialectRoute were never built, and the other six were only reached from inside those screens. Removed with their view models, UI states, routes, nav host entries, the repository behind them, TranslationScaffold, DetailRow, and the 65 strings only they used. The group details screen loses the document repository it stored and never read. The string catalogue test now checks its escapes on a string that stays. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- .../composeResources/values/strings.xml | 65 --- .../repository/DatabaseMantraRepository.kt | 94 ---- .../compose/managers/TranslationScaffold.kt | 92 ---- .../ui/composable/AddArtifactScreen.kt | 406 --------------- .../compose/ui/composable/AddChapterScreen.kt | 326 ------------ .../compose/ui/composable/AddDialectScreen.kt | 342 ------------- .../AddTranslationArtifactVersionScreen.kt | 341 ------------- .../ui/composable/ArtifactDetailScreen.kt | 354 ------------- .../ui/composable/ChapterDetailScreen.kt | 220 -------- .../ui/composable/ChatRoomDetailScreen.kt | 4 - .../ui/composable/TranslateChunkScreen.kt | 275 ---------- .../TranslationArtifactVersionDetailScreen.kt | 310 ------------ .../ui/composable/TranslationChapterScreen.kt | 279 ----------- .../ui/composable/navigation/BennuNavHost.kt | 251 ---------- .../navigation/routes/AddArtifactRoute.kt | 10 - .../navigation/routes/AddChapterRoute.kt | 11 - .../navigation/routes/AddDialectRoute.kt | 10 - .../navigation/routes/AddTranslationRoute.kt | 11 - .../navigation/routes/ArtifactDetailRoute.kt | 11 - .../navigation/routes/ChapterDetailRoute.kt | 11 - .../navigation/routes/TranslateChunkRoute.kt | 12 - .../TranslationArtifactVersionDetailRoute.kt | 11 - .../routes/TranslationChapterRoute.kt | 11 - .../ui/composable/widgets/DetailRow.kt | 14 - .../ui/view/model/AddArtifactViewModel.kt | 186 ------- .../ui/view/model/AddChapterViewModel.kt | 291 ----------- .../ui/view/model/AddDialectViewModel.kt | 164 ------ .../AddTranslationArtifactVersionViewModel.kt | 260 ---------- .../ui/view/model/ArtifactDetailViewModel.kt | 74 --- .../ui/view/model/ChapterDetailViewModel.kt | 72 --- .../ui/view/model/ChatRoomDetailViewModel.kt | 4 - .../ui/view/model/TranslateChunkViewModel.kt | 175 ------- ...anslationArtifactVersionDetailViewModel.kt | 172 ------- .../view/model/TranslationChapterViewModel.kt | 98 ---- .../ui/view/state/AddArtifactUIState.kt | 24 - .../ui/view/state/AddChapterUIState.kt | 33 -- .../ui/view/state/AddDialectUIState.kt | 22 - .../AddTranslationArtifactVersionUIState.kt | 52 -- .../ui/view/state/ArtifactDetailUIState.kt | 21 - .../ui/view/state/ChapterDetailUIState.kt | 17 - .../ui/view/state/TranslateChunkUIState.kt | 25 - ...TranslationArtifactVersionDetailUIState.kt | 48 -- .../view/state/TranslationChapterUIState.kt | 28 -- .../managers/TranslationScaffoldTest.kt | 183 ------- .../TranslationBatchProposalJvmTest.kt | 473 ------------------ .../compose/ui/StringCatalogueJvmTest.kt | 11 +- .../ui/composable/ChatRoomMemberRowJvmTest.kt | 2 - .../composable/GroupSignedWorkRowsJvmTest.kt | 2 - 49 files changed, 6 insertions(+), 5904 deletions(-) delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMantraRepository.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/TranslationScaffold.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddArtifactScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddChapterScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddDialectScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddTranslationArtifactVersionScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ArtifactDetailScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChapterDetailScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslateChunkScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslationArtifactVersionDetailScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslationChapterScreen.kt delete mode 100755 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddArtifactRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddChapterRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddDialectRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddTranslationRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ArtifactDetailRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ChapterDetailRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslateChunkRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslationArtifactVersionDetailRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslationChapterRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/DetailRow.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddArtifactViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddChapterViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddDialectViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddTranslationArtifactVersionViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ArtifactDetailViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChapterDetailViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslateChunkViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslationArtifactVersionDetailViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslationChapterViewModel.kt delete mode 100755 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddArtifactUIState.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddChapterUIState.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddDialectUIState.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddTranslationArtifactVersionUIState.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ArtifactDetailUIState.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChapterDetailUIState.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslateChunkUIState.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslationArtifactVersionDetailUIState.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslationChapterUIState.kt delete mode 100644 composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/TranslationScaffoldTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/TranslationBatchProposalJvmTest.kt diff --git a/CLAUDE.md b/CLAUDE.md index de57265a..42ef01c7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -81,7 +81,7 @@ say — marks itself once at the top: ``` **Budget: 0 title-case strings.** Literals in composables are reported without a budget — -39 remain, all of them terms of a `+` concatenation. +19 remain, all of them terms of a `+` concatenation. ## Every target is 48dp, and every icon has a decided description diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 22f2a2d9..56a7741e 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -28,18 +28,11 @@ Abandoned. Nothing was signed. All Bennu - Add a dialect the group can translate into - Add artifact to library - Add artifact to the group library - Add chapter - Add dialect Add to group - Add translation After this there is no turning back. All broadcasts are queued so that we can manage data usage on metered connections. Any amount ARTICLE - Artifact detail As long as you control your keys there can be no dispute about who YOU actually is. Back Backup confirmation @@ -50,16 +43,11 @@ BIP39 seed with the standard BIP84 derivation path. The profile\'s nostr key comes off the same seed, so these 12 words restore both. Block user Cancel - Chapter detail - Chapter name - Chapter translation - Chapters Choose who to chat with Close Cloud backup Copy URL Could not unlock your phrase. Please try again. - Country Create chat Create new chat Create profile @@ -75,9 +63,6 @@ Currently no messages have been shared.\nBreak the ice. Declined to sign Delete group - Details - Dialect name - Dialects Direct message detail Direct message functionality will be here. Direct message via npub @@ -86,20 +71,12 @@ Download Download and securely store everything needed to recover this profile and the coins it holds. Edit profile - eg. Chapter 1 — The Beginning - eg. First Edition - eg. https://harper.com/2-kill-Bird - eg. Lesotho - eg. Sesotho - eg. st - eg. To Kill a Mocking Bird Emergency kit ENDED Encrypt and back your recovery information up to your Google Drive or iCloud. Enough members took part without you. Enter the name you want to use for your group Enter the name you want to use for your profile - Enter the translation for this chunk Events are indexed so that we can deliver a premium local first experience. Everything else Everything is cryptographical sound. Just announcing your profile to the world. @@ -117,7 +94,6 @@ I have saved my recovery phrase somewhere safe. I understand that if I lose this phone and my recovery phrase, I lose this profile and the funds in its wallet. If you are new to Bennu or just want to create a fresh profile - Initial version label Input npub... or nip05 Introduce yourself Invite @@ -130,7 +106,6 @@ Key Key package management Key recovery - Language Learn more Leave group Remove from group @@ -159,7 +134,6 @@ Name Name (eg. Alan Turing) Name (eg. Group Discussions) - Name of artifact Needs you Needs your review. Network relays @@ -169,29 +143,17 @@ Not backed up yet New chat Next - No artifacts exists in this groups library. - No chapters. - No chapters yet. No chat message relays were found for this user. - No chunks. - No dialects have been defined in this group yet. Add one from the group's detail screen first. - No dialects have been defined in this group. No messages. Go to a profile and send them a message. No one selected yet No one to add yet. No projects exists in this group. No proposal has been abandoned. - No translations yet. - No versions. Not now Nothing is waiting for your signature. Nothing was created and no key exists. It is safe to run it again. Open chat - Original - Original text - Original text (markdown) ✓ Paid - Paste the chapter's markdown. Blank lines separate paragraphs into chunks. Pay Pay now Post @@ -204,11 +166,6 @@ Profiles Projects Proposals - Propose - Propose artifact - Propose chapter - Propose dialect - Propose translation Publish new key package Re-broadcast Asked the members who have not answered to take another look @@ -264,7 +221,6 @@ Something went wrong and we were unable to sign in to your provided profile. Please try again later. Something went wrong and we were unable to sign you up. Please try again later. Something went wrong and we were unable to write a new note. Please try again later. - Source dialect Start Start a group chat Start chat via npub or nip05 @@ -285,12 +241,8 @@ The group has a shared key. The recovery phrase (sometimes called a seed) is a list of 12 English words. It is the only way back to this profile: the key that signs as you, and the wallet that holds your coins, are both derived from it.\n\nOnly you have this phrase. Keep it private — nobody from Bennu will ever ask you for it.\n\nDo not lose it. Write it down and keep it somewhere safe that is not this phone. If you lose both the phone and the phrase, this profile and its funds are gone for good. These are your keys. Keep them safe so they can keep unlocking this profile and its coins, even when you lose or change your phone. - This artifact has no version for a translation to be of. - This artifact has no version for a chapter to attach to. - This chapter has no chunks. This device holds no phrase for the profile that is signed in. This decides who can change the group later. You can't switch afterwards. - This group has no shared key, so it cannot sign them in. This group has not been asked to sign anything yet. This group has not signed anything yet. This is fixed once the ceremony runs. Changing it later means generating a new key. @@ -308,12 +260,6 @@ Could not sign out. Please try again. This will give you write access to the profile. Bennu broadcasts what you publish to a distributed set of relays, so it stays decentralised. - Translate chunk - Translate into which dialect? - Translated text - Translation - Translation detail - Translations Transmit note Trending notes functionality coming soon. In the meantime search for what you are looking for. Try again @@ -322,9 +268,6 @@ Unlocking your phrase… Unsupported event kind Untitled article - Url - Version - Versions View and accept invites you may have received to stay connected with others. View invites Waiting for you @@ -356,15 +299,9 @@ Your profile is almost ready... just getting it's first cryptographic signature together. Your share of it is on this device only. Your wallet backup restores it — nobody else's share can. - Add chapter to %1$s Add people to %1$s Ask all %1$s again Asked again about all %1$s proposals - Chapter %1$s - Chapter %1$s · %2$s words · %3$s characters - Chunk %1$s - Chunks (%1$s) - %1$s/%2$s chunks translated %1$s event(s) still unreadable%2$s %1$s events, signed together Everyone has to be online at the same time — the ceremony can only finish once all %1$s of you have taken part. @@ -393,11 +330,9 @@ %1$s sent a private message to %2$s Shared key for %1$s to join the %1$s chat room. - Translate %1$s Unsupported event kind: %1$s %1$s was created, but %2$s couldn't be added yet. Invite them again from the chat once they're on Bennu. %1$s was created, but its shared key ceremony couldn't be started. Open the chat and start it from the group's details — until then the group has no key of its own. - %1$s words · %2$s characters #%1$s You and %1$s others You aren't following anyone yet. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMantraRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMantraRepository.kt deleted file mode 100644 index 28bd0e10..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMantraRepository.kt +++ /dev/null @@ -1,94 +0,0 @@ -package com.machankura.bennu.compose.database.repository - -import co.touchlab.kermit.Logger -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.CoroutineScope -import com.machankura.bennu.compose.database.BennuDatabase -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.database.model.MantraDialect -import com.machankura.bennu.compose.database.model.MantraTranslationArtifactVersion -import com.machankura.bennu.compose.database.model.MantraTranslationChapter -import com.machankura.bennu.compose.database.model.MantraTranslationChunk -import com.machankura.bennu.compose.database.model.MarmotInnerEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.MantraRepository - -class DatabaseMantraRepository( - val database: BennuDatabase, - val scope: CoroutineScope -): MantraRepository { - - private val logger = Logger.withTag(TAG) - - override suspend fun getArtifacts(chatRoomId: String): List = - database.mantraArtifactDao().getArtifactsByChatRoomId(chatRoomId) - - override suspend fun getArtifact(id: String): MantraArtifact? = - database.mantraArtifactDao().getArtifactById(id) - - override suspend fun getArtifactVersions(artifactId: String): List = - database.mantraArtifactVersionDao().getArtifactVersionsByArtifactId(artifactId) - - override suspend fun getArtifactVersion(id: String): MantraArtifactVersion? = - database.mantraArtifactVersionDao().getArtifactVersionById(id) - - override suspend fun getChaptersForArtifact(artifactId: String): List = - database.mantraChapterDao().getChaptersByArtifactId(artifactId) - - override suspend fun getChaptersForArtifactVersion(artifactVersionId: String): List = - database.mantraChapterDao().getChaptersByArtifactVersionId(artifactVersionId) - - override suspend fun getChapter(id: String): MantraChapter? = - database.mantraChapterDao().getChapterById(id) - - override suspend fun getChunksForChapter(chapterId: String): List = - database.mantraChunkDao().getChunksByChapterId(chapterId) - - override suspend fun getChunk(id: String): MantraChunk? = - database.mantraChunkDao().getChunkById(id) - - override suspend fun getTranslationsForArtifact(artifactId: String): List = - database.mantraTranslationArtifactVersionDao().getTranslationsByArtifactId(artifactId) - - override suspend fun getTranslation(id: String): MantraTranslationArtifactVersion? = - database.mantraTranslationArtifactVersionDao().getTranslationById(id) - - override suspend fun getTranslationsForArtifactVersion(artifactVersionId: String): List = - database.mantraTranslationArtifactVersionDao().getTranslationsByArtifactVersionId(artifactVersionId) - - override suspend fun getTranslationChapter(id: String): MantraTranslationChapter? = - database.mantraTranslationChapterDao().getTranslationChapterById(id) - - override suspend fun getTranslationChapters(translationArtifactVersionId: String): List = - database.mantraTranslationChapterDao().getTranslationChaptersByTranslationArtifactVersionId(translationArtifactVersionId) - - override suspend fun getTranslationChunks(translationChapterId: String): List = - database.mantraTranslationChunkDao().getTranslationChunksByTranslationChapterId(translationChapterId) - - override suspend fun getDialects(chatRoomId: String): List = - database.mantraDialectDao().getDialectsByChatRoomId(chatRoomId) - - override suspend fun getDialect(id: String): MantraDialect? = - database.mantraDialectDao().getDialectById(id) - - override suspend fun addArtifactVersion( - localChatRoom: LocalChatRoom, - artifactId: HexKey, - versionLabel: String, - userPublicKey: HexKey, - ): MantraArtifactVersion? { - return database.mantraDao().addArtifactVersion( - localChatRoom = localChatRoom, - artifactId = artifactId, - versionLabel = versionLabel, - userPublicKey = userPublicKey - ) - } - - companion object { - private const val TAG = "DatabaseMantraRepository" - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/TranslationScaffold.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/TranslationScaffold.kt deleted file mode 100644 index 83081bf8..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/TranslationScaffold.kt +++ /dev/null @@ -1,92 +0,0 @@ -package com.machankura.bennu.compose.managers - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraTranslationChapter -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent - -/** - * The rows that join a translation to the chapters it is a translation of. - * - * A translation chapter carries no words. It is `(translation, chapter, - * position)` and nothing else, and it exists so that a translated chunk has - * somewhere to hang: a translation without one for a chapter is a translation - * that chapter cannot be worked on in. - * - * Both ends of that join arrive on their own schedule -- a chapter is signed - * into an artifact that already has translations, a translation is started on - * an artifact that already has chapters -- so the same scaffolding is built - * from either side and, when the two miss each other, afterwards. One function - * for all three, because three copies of a cross product is three chances to - * disagree about what a translation covers. - */ -object TranslationScaffold { - - /** - * A source chapter, reduced to what a translation chapter needs of it: - * which chapter, and where it sits. - * - * Taken as this rather than as a [MantraChapter] because the chapter is not - * always a row yet. When a chapter is signed into an artifact, the - * scaffolding goes out in the same breath as the chapter itself, against an - * id that exists only as the unsigned event a session is about to sign. - */ - data class SourceChapter( - val id: HexKey, - val index: Int, - ) { - companion object { - fun of(chapter: MantraChapter) = SourceChapter(id = chapter.id, index = chapter.index) - } - } - - /** - * A translation chapter for every pair of [translationArtifactVersionIds] - * and [chapters], in that nesting: a translation's chapters stay together - * and in reading order. - * - * The order is the order a session will sign them in and the order they - * will be applied in, so it is fixed here rather than left to a caller. - * - * [createdAt] is stamped on all of them rather than read per event, so that - * a scaffolding proposed as one act reads as one -- the timestamp of the - * chapter or the translation that occasioned it, not of whichever moment - * each template happened to be built in. - */ - fun chaptersOf( - translationArtifactVersionIds: List, - chapters: List, - createdAt: Long, - ): List> = - translationArtifactVersionIds.flatMap { translationArtifactVersionId -> - chapters.map { chapter -> - TranslationChapterEvent.build( - translationArtifactVersionId = translationArtifactVersionId, - chapterId = chapter.id, - // The source chapter's own position, never this list's: a - // catch-up proposes a subset, so counting the list would - // renumber the chapters it happens to be filling in. - index = chapter.index, - createdAt = createdAt, - ) - } - } - - /** - * The source chapters a translation has nothing for yet. - * - * Matched on the source chapter each translation chapter names rather than - * on how many there are of each. A translation that is missing its second - * chapter and has picked up its third is not a translation that is missing - * its last one, and a count would say it was. - */ - fun chaptersMissingFrom( - translationChapters: List, - sourceChapters: List, - ): List { - val covered = translationChapters.mapTo(mutableSetOf()) { it.chapterId } - - return sourceChapters.filterNot { it.id in covered } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddArtifactScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddArtifactScreen.kt deleted file mode 100644 index 0e84f739..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddArtifactScreen.kt +++ /dev/null @@ -1,406 +0,0 @@ -package com.machankura.bennu.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.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.text.input.rememberTextFieldState -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Add -import androidx.compose.material.icons.filled.DriveFileRenameOutline -import androidx.compose.material.icons.filled.Label -import androidx.compose.material.icons.filled.Link -import androidx.compose.material.icons.filled.LocalOffer -import androidx.compose.material.icons.filled.MoreVert -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.BottomAppBarDefaults -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.FilterChip -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.OutlinedTextFieldDefaults -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.NostrRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.ChatRoomDetailRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.state.ChatRoomMessagingUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ImplementationPendingRoute -import com.machankura.bennu.compose.ui.view.model.AddArtifactViewModel -import com.machankura.bennu.compose.ui.view.state.AddArtifactUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.add_artifact_to_the_group_library -import bennu.composeapp.generated.resources.direct_message_detail -import bennu.composeapp.generated.resources.direct_message_functionality_will_be_here -import bennu.composeapp.generated.resources.eg_first_edition -import bennu.composeapp.generated.resources.eg_https_harper_com_2_kill_bird -import bennu.composeapp.generated.resources.eg_to_kill_a_mocking_bird -import bennu.composeapp.generated.resources.initial_version_label -import bennu.composeapp.generated.resources.name_of_artifact -import bennu.composeapp.generated.resources.no_dialects_have_been_defined_in_this_group -import bennu.composeapp.generated.resources.propose_artifact -import bennu.composeapp.generated.resources.source_dialect -import bennu.composeapp.generated.resources.url -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) -@Composable -fun AddArtifactScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialAddArtifactUIState: AddArtifactUIState = AddArtifactUIState.Loading, - nostrRepository: NostrRepository, - chatRepository: ChatRepository, - mantraRepository: MantraRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val addArtifactViewModel: AddArtifactViewModel = viewModel( - factory = AddArtifactViewModel.factory( - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddArtifactUIState = initialAddArtifactUIState, - nostrRepository = nostrRepository, - chatRepository = chatRepository, - activeUserPublicKey = activeUserPublicKey, - mantraRepository = mantraRepository, - frostSigningRepository = frostSigningRepository - ) - ) - - ScreenStateTransition(addArtifactViewModel.addArtifactUIState) { uiState -> - when (val addArtifactUIState = uiState) { - is AddArtifactUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer( - modifier = Modifier.height(MaterialTheme.spacing.space600) - ) - Text( - text = addArtifactUIState.message, - ) - } - } - is AddArtifactUIState.Loaded -> { - val nameFieldState = rememberTextFieldState() - val urlFieldState = rememberTextFieldState() - val versionLabelFieldState = rememberTextFieldState("1.0") - - // The id of the group dialect this artifact is written in. Null until - // one is picked; dialects are defined from the group detail screen. - var selectedDialectId: String? by remember { mutableStateOf(null) } - - // The two things the form cannot ask for again. A dialect has to - // already exist and nothing here can create one; a shared key has to - // have been ceremonied and this is not where that happens. Either - // missing is a dead end rather than something to propose and be told - // about afterwards, and the button says so. - val canAddArtifact = selectedDialectId != null && addArtifactUIState.canSign - - // imePadding: this screen has a text field, and without it the software - // keyboard covers whatever is being typed into. - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { - addArtifactUIState.localChatRoom.RenderChatRoomTitleText() - }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_artifact), - icon = { Icon(Icons.Default.Add, contentDescription = "Propose artifact") }, - enabled = canAddArtifact, - onClick = { - addArtifactViewModel.addArtifact( - localChatRoom = addArtifactUIState.localChatRoom, - nameField = nameFieldState, - urlField = urlFieldState, - versionLabelField = versionLabelFieldState, - dialectId = selectedDialectId, - onSuccess = { sessionId -> - // Onto the session rather than to the - // artifact. Nothing has been created yet - // -- the artifact appears when enough - // members sign -- so a detail screen for - // a row that does not exist would read as - // a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - onFailure = { - onNavigateToRoute.invoke( - ImplementationPendingRoute("Failed artifact") - ) - } - ) - - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() - ) { - // TODO: Check that we have direct message relays for this user... - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Text(stringResource(Res.string.add_artifact_to_the_group_library)) - - if (!addArtifactUIState.canSign) { - Text( - text = "This group has no shared key, so it cannot sign an " + - "artifact into its library. Run a shared key ceremony first.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - - OutlinedTextField( - modifier = Modifier.fillMaxWidth() - .background(BottomAppBarDefaults.containerColor), - state = nameFieldState, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon( - Icons.Default.DriveFileRenameOutline, - contentDescription = "Name of the artifact" - ) - }, - label = { - Text( - text = stringResource(Res.string.name_of_artifact) - ) - }, - placeholder = { - Text( - text = stringResource(Res.string.eg_to_kill_a_mocking_bird) - ) - }, - ) - - OutlinedTextField( - modifier = Modifier.fillMaxWidth() - .background(BottomAppBarDefaults.containerColor), - state = urlFieldState, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon( - Icons.Default.Link, - contentDescription = "Link to the artifact" - ) - }, - label = { - Text( - text = stringResource(Res.string.url) - ) - }, - placeholder = { - Text( - text = stringResource(Res.string.eg_https_harper_com_2_kill_bird) - ) - }, - ) - - OutlinedTextField( - modifier = Modifier.fillMaxWidth() - .background(BottomAppBarDefaults.containerColor), - state = versionLabelFieldState, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon( - Icons.Default.LocalOffer, - contentDescription = "Verison label" - ) - }, - label = { - Text( - text = stringResource(Res.string.initial_version_label) - ) - }, - placeholder = { - Text( - text = stringResource(Res.string.eg_first_edition) - ) - }, - ) - - Text(stringResource(Res.string.source_dialect)) - - if (addArtifactUIState.dialects.isEmpty()) { - Text( - text = stringResource(Res.string.no_dialects_have_been_defined_in_this_group), - style = MaterialTheme.typography.bodySmall - ) - } else { - FlowRow( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - addArtifactUIState.dialects.forEach { dialect -> - FilterChip( - selected = selectedDialectId == dialect.id, - onClick = { selectedDialectId = dialect.id }, - label = { Text(dialect.name) } - ) - } - } - } - - // TODO: Add Visibility - } - } - } - } - AddArtifactUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding( - MaterialTheme.spacing.space250 - ), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - - Spacer( - modifier = Modifier.weight(1f) - ) - Text( - text = stringResource(Res.string.direct_message_detail), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - - Text( - text = stringResource(Res.string.direct_message_functionality_will_be_here), - style = MaterialTheme.typography.bodySmall, - textAlign = TextAlign.Center - ) - - LoadingDataIndicator( - fillScreen = false - ) - - Spacer( - modifier = Modifier.weight(2f) - ) - } - } - } - } - - LaunchedEffect(true) { - if (initialAddArtifactUIState == AddArtifactUIState.Loading) { - addArtifactViewModel.initiateChatRoomDetail() - } - } -} - -@ConformancePreviews -@Composable -private fun AddArtifactScreenPreview() { - BennuTheme { - Surface( - modifier = Modifier.fillMaxSize() - ) { - AddArtifactScreen( - activeUserPublicKey = "", - chatRoomId = "publicKey", - relayHint = null, - initialAddArtifactUIState = AddArtifactUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "", - userPublicKey = "", - subject = "Message title", - description = "See something. Say somethin", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = null - ), - ) - ), - nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateToRoute = {}, - onNavigateBack = {}, - ) - } - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddChapterScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddChapterScreen.kt deleted file mode 100644 index f5fdd087..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddChapterScreen.kt +++ /dev/null @@ -1,326 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.text.input.rememberTextFieldState -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Add -import androidx.compose.material.icons.filled.DriveFileRenameOutline -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.text.Markdown -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ImplementationPendingRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.AddChapterViewModel -import com.machankura.bennu.compose.ui.view.state.AddChapterUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.add_chapter -import bennu.composeapp.generated.resources.chapter_name -import bennu.composeapp.generated.resources.eg_chapter_1_the_beginning -import bennu.composeapp.generated.resources.original_text_markdown -import bennu.composeapp.generated.resources.paste_the_chapter_s_markdown_blank_lines -import bennu.composeapp.generated.resources.propose_chapter -import bennu.composeapp.generated.resources.this_artifact_has_no_version_for_a_chapter -import bennu.composeapp.generated.resources.add_chapter_to -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun AddChapterScreen( - activeUserPublicKey: HexKey, - artifactId: String, - chatRoomId: String, - relayHint: String?, - initialAddChapterUIState: AddChapterUIState = AddChapterUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val addChapterViewModel: AddChapterViewModel = viewModel( - factory = AddChapterViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifactId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddChapterUIState = initialAddChapterUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - ) - - ScreenStateTransition(addChapterViewModel.addChapterUIState) { uiState -> - when (val addChapterUIState = uiState) { - is AddChapterUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - Text(text = addChapterUIState.message) - } - } - - is AddChapterUIState.Loaded -> { - val nameFieldState = rememberTextFieldState() - val originalTextFieldState = rememberTextFieldState() - - // Live counts / paragraph (chunk) preview from the markdown text. - val originalText = originalTextFieldState.text.toString() - val wordCount = Markdown.wordCount(originalText) - val characterCount = Markdown.characterCount(originalText) - val paragraphCount = Markdown.splitParagraphs(originalText).size - - // A chapter hangs off a version, and the group has to be able to - // sign; without both there is nothing this screen can propose. - val artifactVersion = addChapterUIState.artifactVersion - - // The chapter and a chunk per paragraph are signed in one session, - // and a session signs a bounded number of events. Past that the - // chapter has to be split in two, which is worth saying while there - // is still a cursor in the text rather than after a failed propose. - val tooManyChunks = paragraphCount > AddChapterViewModel.MAX_CHUNKS_PER_CHAPTER - - val canProposeChapter = artifactVersion != null && - addChapterUIState.canSign && - paragraphCount > 0 && - !tooManyChunks - - // imePadding: this screen has a text field, and without it the software - // keyboard covers whatever is being typed into. - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.add_chapter_to, addChapterUIState.artifact.name)) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_chapter), - icon = { Icon(Icons.Default.Add, contentDescription = "Propose chapter") }, - enabled = canProposeChapter, - onClick = { - if (artifactVersion == null) return@ExtendedFab - - addChapterViewModel.addChapter( - localChatRoom = addChapterUIState.localChatRoom, - artifactVersion = artifactVersion, - nameField = nameFieldState, - originalTextField = originalTextFieldState, - onSuccess = { sessionId -> - // Onto the session rather than back to - // the artifact. Nothing has been created - // yet -- the chapter appears when enough - // members sign -- so landing on the list - // it is not in would read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - onFailure = { - onNavigateToRoute.invoke( - ImplementationPendingRoute("Failed chapter") - ) - } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize().padding(MaterialTheme.spacing.space250), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - if (!addChapterUIState.canSign) { - Text( - text = "This group has no shared key, so it cannot sign a " + - "chapter into existence. Run a shared key ceremony first.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } else if (artifactVersion == null) { - Text( - text = stringResource(Res.string.this_artifact_has_no_version_for_a_chapter), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } else if (tooManyChunks) { - Text( - text = "$paragraphCount chunks is more than the group can sign in " + - "one go. Split the chapter so that no part of it is over " + - "${AddChapterViewModel.MAX_CHUNKS_PER_CHAPTER} paragraphs.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = nameFieldState, - leadingIcon = { - Icon( - Icons.Default.DriveFileRenameOutline, - contentDescription = "Name of the chapter" - ) - }, - label = { Text(stringResource(Res.string.chapter_name)) }, - placeholder = { Text(stringResource(Res.string.eg_chapter_1_the_beginning)) }, - ) - - OutlinedTextField( - modifier = Modifier.fillMaxWidth().weight(1f), - state = originalTextFieldState, - label = { Text(stringResource(Res.string.original_text_markdown)) }, - placeholder = { Text(stringResource(Res.string.paste_the_chapter_s_markdown_blank_lines)) }, - ) - - Text( - // The chunk count is what the group is asked to sign - // alongside the chapter, so it is a count of the work - // being proposed rather than a curiosity about the text. - text = "$wordCount words · $characterCount characters · " + - "$paragraphCount ${if (paragraphCount == 1) "chunk" else "chunks"} " + - "of ${AddChapterViewModel.MAX_CHUNKS_PER_CHAPTER}", - style = MaterialTheme.typography.labelMedium, - color = if (tooManyChunks) { - MaterialTheme.colorScheme.error - } else { - MaterialTheme.typography.labelMedium.color - } - ) - } - } - } - - AddChapterUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - Spacer(modifier = Modifier.weight(1f)) - Text( - text = stringResource(Res.string.add_chapter), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - LoadingDataIndicator(fillScreen = false) - Spacer(modifier = Modifier.weight(2f)) - } - } - } - } - - LaunchedEffect(true) { - if (initialAddChapterUIState == AddChapterUIState.Loading) { - addChapterViewModel.initiateAddChapter() - } - } -} - -@ConformancePreviews -@Composable -private fun AddChapterScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - AddChapterScreen( - activeUserPublicKey = "", - artifactId = "artifactId", - chatRoomId = "chatRoomId", - relayHint = null, - initialAddChapterUIState = AddChapterUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "chatRoomId", - userPublicKey = "", - subject = "Message title", - description = "See something. Say somethin", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = null - ), - ), - artifact = MantraArtifact( - id = "artifactId", - publicKey = "author", - name = "To Kill a Mockingbird", - url = "https://harper.com/2-kill-Bird", - visibility = "private", - dialectId = "dialectId", - license = "cc", - chatRoomId = "chatRoomId", - signature = "" - ), - artifactVersion = MantraArtifactVersion( - id = "artifactVersionId", - artifactId = "artifactId", - publicKey = "author", - versionLabel = "1.0", - chatRoomId = "chatRoomId", - signature = "" - ), - canSign = true, - ), - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateToRoute = {}, - onNavigateBack = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddDialectScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddDialectScreen.kt deleted file mode 100644 index 137b9e39..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddDialectScreen.kt +++ /dev/null @@ -1,342 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.text.input.rememberTextFieldState -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Add -import androidx.compose.material.icons.filled.Public -import androidx.compose.material.icons.filled.Title -import androidx.compose.material.icons.filled.Translate -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.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.NostrRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ImplementationPendingRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.AddDialectViewModel -import com.machankura.bennu.compose.ui.view.state.AddDialectUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.add_a_dialect_the_group_can_translate_into -import bennu.composeapp.generated.resources.add_dialect -import bennu.composeapp.generated.resources.country -import bennu.composeapp.generated.resources.dialect_name -import bennu.composeapp.generated.resources.eg_lesotho -import bennu.composeapp.generated.resources.eg_sesotho -import bennu.composeapp.generated.resources.eg_st -import bennu.composeapp.generated.resources.language -import bennu.composeapp.generated.resources.propose_dialect -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) -@Composable -fun AddDialectScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialAddDialectUIState: AddDialectUIState = AddDialectUIState.Loading, - nostrRepository: NostrRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val addDialectViewModel: AddDialectViewModel = viewModel( - factory = AddDialectViewModel.factory( - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddDialectUIState = initialAddDialectUIState, - nostrRepository = nostrRepository, - chatRepository = chatRepository, - activeUserPublicKey = activeUserPublicKey, - frostSigningRepository = frostSigningRepository - ) - ) - - ScreenStateTransition(addDialectViewModel.addDialectUIState) { uiState -> - when (val addDialectUIState = uiState) { - is AddDialectUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer( - modifier = Modifier.height(MaterialTheme.spacing.space600) - ) - Text( - text = addDialectUIState.message, - ) - } - } - is AddDialectUIState.Loaded -> { - val nameFieldState = rememberTextFieldState() - val countryFieldState = rememberTextFieldState() - val languageFieldState = rememberTextFieldState() - - // imePadding: this screen has a text field, and without it the software - // keyboard covers whatever is being typed into. - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { - addDialectUIState.localChatRoom.RenderChatRoomTitleText() - }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_dialect), - icon = { Icon(Icons.Default.Add, contentDescription = "Propose dialect") }, - enabled = addDialectUIState.canSign, - onClick = { - addDialectViewModel.addDialect( - localChatRoom = addDialectUIState.localChatRoom, - nameField = nameFieldState, - countryField = countryFieldState, - languageField = languageFieldState, - onSuccess = { sessionId -> - // Onto the session rather than back to - // the group. Nothing has been created - // yet -- the dialect appears when enough - // members sign -- so landing on the list - // it is not in would read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - onFailure = { - onNavigateToRoute.invoke( - ImplementationPendingRoute("Failed dialect") - ) - } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() - ) { - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Text(stringResource(Res.string.add_a_dialect_the_group_can_translate_into)) - - if (!addDialectUIState.canSign) { - Text( - text = "This group has no shared key, so it cannot sign a " + - "dialect into existence. Run a shared key ceremony first.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - - OutlinedTextField( - modifier = Modifier.fillMaxWidth() - .background(BottomAppBarDefaults.containerColor), - state = nameFieldState, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon( - Icons.Default.Title, - contentDescription = "Name of the dialect" - ) - }, - label = { - Text( - text = stringResource(Res.string.dialect_name) - ) - }, - placeholder = { - Text( - text = stringResource(Res.string.eg_sesotho) - ) - }, - ) - - OutlinedTextField( - modifier = Modifier.fillMaxWidth() - .background(BottomAppBarDefaults.containerColor), - state = countryFieldState, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon( - Icons.Default.Public, - contentDescription = "Country of the dialect" - ) - }, - label = { - Text( - text = stringResource(Res.string.country) - ) - }, - placeholder = { - Text( - text = stringResource(Res.string.eg_lesotho) - ) - }, - ) - - OutlinedTextField( - modifier = Modifier.fillMaxWidth() - .background(BottomAppBarDefaults.containerColor), - state = languageFieldState, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon( - Icons.Default.Translate, - contentDescription = "Language of the dialect" - ) - }, - label = { - Text( - text = stringResource(Res.string.language) - ) - }, - placeholder = { - Text( - text = stringResource(Res.string.eg_st) - ) - }, - ) - } - } - } - } - AddDialectUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding( - MaterialTheme.spacing.space250 - ), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - - Spacer( - modifier = Modifier.weight(1f) - ) - Text( - text = stringResource(Res.string.add_dialect), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - - LoadingDataIndicator( - fillScreen = false - ) - - Spacer( - modifier = Modifier.weight(2f) - ) - } - } - } - } - - LaunchedEffect(true) { - if (initialAddDialectUIState == AddDialectUIState.Loading) { - addDialectViewModel.initiateAddDialect() - } - } -} - -@ConformancePreviews -@Composable -private fun AddDialectScreenPreview() { - BennuTheme { - Surface( - modifier = Modifier.fillMaxSize() - ) { - AddDialectScreen( - activeUserPublicKey = "", - chatRoomId = "publicKey", - relayHint = null, - initialAddDialectUIState = AddDialectUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "", - userPublicKey = "", - subject = "Message title", - description = "See something. Say somethin", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = null - ), - ) - ), - nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateToRoute = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddTranslationArtifactVersionScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddTranslationArtifactVersionScreen.kt deleted file mode 100644 index b55fac5b..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddTranslationArtifactVersionScreen.kt +++ /dev/null @@ -1,341 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Translate -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.FilterChip -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.MantraDialect -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.managers.FrostSigningManager -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ImplementationPendingRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.AddTranslationArtifactVersionViewModel -import com.machankura.bennu.compose.ui.view.state.AddTranslationArtifactVersionUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.add_translation -import bennu.composeapp.generated.resources.propose_translation -import bennu.composeapp.generated.resources.this_artifact_has_no_version_for_a -import bennu.composeapp.generated.resources.translate_into_which_dialect -import bennu.composeapp.generated.resources.translate -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) -@Composable -fun AddTranslationArtifactVersionScreen( - activeUserPublicKey: HexKey, - artifactId: String, - chatRoomId: String, - relayHint: String?, - initialAddTranslationArtifactVersionUIState: AddTranslationArtifactVersionUIState = AddTranslationArtifactVersionUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val addTranslationArtifactVersionViewModel: AddTranslationArtifactVersionViewModel = viewModel( - factory = AddTranslationArtifactVersionViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifactId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddTranslationArtifactVersionUIState = initialAddTranslationArtifactVersionUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - ) - - ScreenStateTransition(addTranslationArtifactVersionViewModel.addTranslationArtifactVersionUIState) { uiState -> - when (val addTranslationUIState = uiState) { - is AddTranslationArtifactVersionUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - Text(text = addTranslationUIState.message) - } - } - - is AddTranslationArtifactVersionUIState.Loaded -> { - // A translation is into a dialect the group already signed into - // existence. Nothing is chosen to begin with: picking the first one - // for somebody would be choosing the language of the work. - var selectedDialectId: String? by remember { mutableStateOf(null) } - val selectedDialect = addTranslationUIState.dialects - .firstOrNull { dialect -> dialect.id == selectedDialectId } - - // A translation hangs off a version, and the group has to be able to - // sign; without both there is nothing this screen can propose. - val artifactVersion = addTranslationUIState.artifactVersion - val chapterCount = addTranslationUIState.chapters.size - - // The translation and a chapter apiece are signed together, and a - // session signs a bounded number of events -- so a long artifact is - // proposed in more than one, and the admins answer once per - // session. That is a number worth seeing before the tap. - val sessionCount = 1 + ( - (chapterCount - AddTranslationArtifactVersionViewModel.MAX_CHAPTERS_PER_TRANSLATION) - .coerceAtLeast(0) + FrostSigningManager.MAX_BATCH_SIZE - 1 - ) / FrostSigningManager.MAX_BATCH_SIZE - - val canProposeTranslation = artifactVersion != null && - selectedDialect != null && - addTranslationUIState.canSign - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.translate, addTranslationUIState.artifact.name)) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_translation), - icon = { Icon(Icons.Default.Translate, contentDescription = "Propose translation") }, - enabled = canProposeTranslation, - onClick = { - if (artifactVersion == null || selectedDialect == null) return@ExtendedFab - - addTranslationArtifactVersionViewModel.addTranslation( - localChatRoom = addTranslationUIState.localChatRoom, - artifact = addTranslationUIState.artifact, - artifactVersion = artifactVersion, - dialect = selectedDialect, - chapters = addTranslationUIState.chapters, - onSuccess = { sessionId -> - // Onto the session rather than back to - // the artifact. Nothing has been created - // yet -- the translation appears when - // enough members sign -- so landing on - // the list it is not in would read as a - // failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - onFailure = { - onNavigateToRoute.invoke( - ImplementationPendingRoute("Failed translation") - ) - } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize().padding(MaterialTheme.spacing.space250), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - if (!addTranslationUIState.canSign) { - Text( - text = "This group has no shared key, so it cannot sign a " + - "translation into existence. Run a shared key ceremony first.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } else if (artifactVersion == null) { - Text( - text = stringResource(Res.string.this_artifact_has_no_version_for_a), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - - Text(stringResource(Res.string.translate_into_which_dialect)) - - if (addTranslationUIState.dialects.isEmpty()) { - // The only way out of this screen, and it is not on it: - // a dialect is the group's too, and asking for one is - // its own quorum from the room's own detail screen. - Text( - text = "This group has no dialects yet. Add one from the group's " + - "details before translating anything into it.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - - FlowRow( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - addTranslationUIState.dialects.forEach { dialect -> - FilterChip( - selected = selectedDialectId == dialect.id, - onClick = { selectedDialectId = dialect.id }, - label = { Text(dialect.name) } - ) - } - } - - Text( - // What the group is being asked to sign, counted before - // the tap rather than described after it: the chapters - // are the rest of the batch. The empty case is worth - // its own sentence, so that a translation of an artifact - // nobody has written into yet does not read as broken. - text = if (chapterCount == 0) { - "The artifact has no chapters yet, so the group would sign the " + - "translation on its own. Chapters signed afterwards are put " + - "into it as they are added." - } else { - "The group signs the translation and " + - "$chapterCount ${if (chapterCount == 1) "chapter" else "chapters"}" + - (if (sessionCount == 1) "" else ", in $sessionCount sessions to sign") + - ". Chunks are translated one at a time afterwards." - }, - style = MaterialTheme.typography.labelMedium, - ) - } - } - } - - AddTranslationArtifactVersionUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - Spacer(modifier = Modifier.weight(1f)) - Text( - text = stringResource(Res.string.add_translation), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - LoadingDataIndicator(fillScreen = false) - Spacer(modifier = Modifier.weight(2f)) - } - } - } - } - - LaunchedEffect(true) { - if (initialAddTranslationArtifactVersionUIState == AddTranslationArtifactVersionUIState.Loading) { - addTranslationArtifactVersionViewModel.initiateAddTranslation() - } - } -} - -@ConformancePreviews -@Composable -private fun AddTranslationArtifactVersionScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - AddTranslationArtifactVersionScreen( - activeUserPublicKey = "", - artifactId = "artifactId", - chatRoomId = "chatRoomId", - relayHint = null, - initialAddTranslationArtifactVersionUIState = AddTranslationArtifactVersionUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "", - userPublicKey = "", - subject = "Message title", - description = "See something. Say somethin", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = null - ), - ), - artifact = MantraArtifact( - id = "artifactId", - publicKey = "author", - name = "To Kill a Mockingbird", - url = "https://harper.com/2-kill-Bird", - visibility = "private", - dialectId = "dialectId", - license = "cc", - chatRoomId = "chatRoomId", - signature = "" - ), - dialects = listOf( - MantraDialect( - id = "dialectId", - publicKey = "author", - name = "Sesotho", - country = "Lesotho", - language = "st", - chatRoomId = "chatRoomId", - signature = "" - ) - ), - artifactVersion = MantraArtifactVersion( - id = "artifactVersionId", - artifactId = "artifactId", - publicKey = "author", - versionLabel = "1.0", - chatRoomId = "chatRoomId", - signature = "" - ), - canSign = true, - ), - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateToRoute = {}, - onNavigateBack = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ArtifactDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ArtifactDetailScreen.kt deleted file mode 100644 index ce39a59a..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ArtifactDetailScreen.kt +++ /dev/null @@ -1,354 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.layout.width -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Article -import androidx.compose.material.icons.filled.PostAdd -import androidx.compose.material.icons.filled.Translate -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.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.composable.widgets.DetailRow -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddChapterRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddTranslationRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ChapterDetailRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.navigation.routes.TranslationArtifactVersionDetailRoute -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.ArtifactDetailViewModel -import com.machankura.bennu.compose.ui.view.state.ArtifactDetailUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.add_chapter -import bennu.composeapp.generated.resources.add_translation -import bennu.composeapp.generated.resources.artifact_detail -import bennu.composeapp.generated.resources.chapters -import bennu.composeapp.generated.resources.details -import bennu.composeapp.generated.resources.no_chapters_yet -import bennu.composeapp.generated.resources.no_translations_yet -import bennu.composeapp.generated.resources.no_versions -import bennu.composeapp.generated.resources.translations -import bennu.composeapp.generated.resources.version -import bennu.composeapp.generated.resources.versions -import bennu.composeapp.generated.resources.chapter -import bennu.composeapp.generated.resources.words_characters -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun ArtifactDetailScreen( - activeUserPublicKey: HexKey, - artifactId: String, - chatRoomId: String, - relayHint: String?, - initialArtifactDetailUIState: ArtifactDetailUIState = ArtifactDetailUIState.Loading, - mantraRepository: MantraRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val artifactDetailViewModel: ArtifactDetailViewModel = viewModel( - factory = ArtifactDetailViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifactId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialArtifactDetailUIState = initialArtifactDetailUIState, - mantraRepository = mantraRepository, - ) - ) - - ScreenStateTransition(artifactDetailViewModel.artifactDetailUIState) { uiState -> - when (val artifactDetailUIState = uiState) { - is ArtifactDetailUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - Text(text = artifactDetailUIState.message) - } - } - - is ArtifactDetailUIState.Loaded -> { - val artifact = artifactDetailUIState.artifact - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(artifact.name) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - } - ) { innerPadding -> - LazyColumn( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize().padding(MaterialTheme.spacing.space250), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - // Chapters - item { - Text( - text = stringResource(Res.string.chapters), - style = MaterialTheme.typography.labelMedium - ) - } - if (artifactDetailUIState.chapters.isEmpty()) { - item { Text(stringResource(Res.string.no_chapters_yet)) } - } else { - items( - items = artifactDetailUIState.chapters, - key = { chapter -> chapter.id } - ) { chapter -> - Card( - onClick = { - onNavigateToRoute.invoke( - ChapterDetailRoute( - activeUserPublicKey = activeUserPublicKey, - chapterId = chapter.id, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) { - ListItem( - leadingContent = { - Icon( - Icons.Default.Article, - contentDescription = "Chapter" - ) - }, - overlineContent = { Text(stringResource(Res.string.chapter, chapter.index)) }, - headlineContent = { Text(chapter.name) }, - supportingContent = { - Text(stringResource(Res.string.words_characters, chapter.wordCount, chapter.characterCount)) - } - ) - } - } - } - - item { - TextButton( - enabled = artifactDetailUIState.versions.isNotEmpty(), - onClick = { - onNavigateToRoute.invoke( - AddChapterRoute( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifact.id, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) { - Icon( - Icons.Default.PostAdd, - contentDescription = "Add chapter" - ) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) - Text(stringResource(Res.string.add_chapter)) - } - } - - item { HorizontalDivider() } - - // Translations - item { - Text( - text = stringResource(Res.string.translations), - style = MaterialTheme.typography.labelMedium - ) - } - if (artifactDetailUIState.translations.isEmpty()) { - item { Text(stringResource(Res.string.no_translations_yet)) } - } else { - items( - items = artifactDetailUIState.translations, - key = { translation -> translation.id } - ) { translation -> - Card( - onClick = { - onNavigateToRoute.invoke( - TranslationArtifactVersionDetailRoute( - activeUserPublicKey = activeUserPublicKey, - translationArtifactVersionId = translation.id, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) { - ListItem( - leadingContent = { - Icon( - Icons.Default.Translate, - contentDescription = "Translation" - ) - }, - headlineContent = { Text(translation.name) }, - supportingContent = { Text(translation.visibility) } - ) - } - } - } - - item { - TextButton( - enabled = artifactDetailUIState.versions.isNotEmpty(), - onClick = { - onNavigateToRoute.invoke( - AddTranslationRoute( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifact.id, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) { - Icon( - Icons.Default.Translate, - contentDescription = "Add translation" - ) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) - Text(stringResource(Res.string.add_translation)) - } - } - - item { HorizontalDivider() } - - // Details - item { - Text( - text = stringResource(Res.string.details), - style = MaterialTheme.typography.labelMedium - ) - } - item { - Card { - DetailRow(label = "Name", value = artifact.name) - DetailRow(label = "Url", value = artifact.url) - DetailRow(label = "Visibility", value = artifact.visibility) - DetailRow(label = "License", value = artifact.license) - DetailRow(label = "Dialect", value = artifact.dialectId) - DetailRow(label = "Author", value = artifact.publicKey) - DetailRow(label = "Created", value = artifact.createdAt.toString()) - } - } - - // Versions - item { - Text( - text = stringResource(Res.string.versions), - style = MaterialTheme.typography.labelMedium - ) - } - if (artifactDetailUIState.versions.isEmpty()) { - item { Text(stringResource(Res.string.no_versions)) } - } else { - items( - items = artifactDetailUIState.versions, - key = { version -> version.id } - ) { version -> - Card { - ListItem( - headlineContent = { Text(version.versionLabel) }, - overlineContent = { Text(stringResource(Res.string.version)) } - ) - } - } - } - } - } - } - - ArtifactDetailUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - Spacer(modifier = Modifier.weight(1f)) - Text( - text = stringResource(Res.string.artifact_detail), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - LoadingDataIndicator(fillScreen = false) - Spacer(modifier = Modifier.weight(2f)) - } - } - } - } - - LaunchedEffect(true) { - if (initialArtifactDetailUIState == ArtifactDetailUIState.Loading) { - artifactDetailViewModel.initiateArtifactDetail() - } - } -} - -@ConformancePreviews -@Composable -private fun ArtifactDetailScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - ArtifactDetailScreen( - activeUserPublicKey = "", - artifactId = "artifactId", - chatRoomId = "chatRoomId", - relayHint = null, - initialArtifactDetailUIState = ArtifactDetailUIState.Loaded( - artifact = MantraArtifact( - id = "artifactId", - publicKey = "author", - name = "To Kill a Mockingbird", - url = "https://harper.com/2-kill-Bird", - visibility = "private", - dialectId = "dialectId", - license = "cc", - chatRoomId = "chatRoomId", - signature = "" - ) - ), - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - onNavigateToRoute = {}, - onNavigateBack = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChapterDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChapterDetailScreen.kt deleted file mode 100644 index cdb12652..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChapterDetailScreen.kt +++ /dev/null @@ -1,220 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Segment -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.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.ChapterDetailViewModel -import com.machankura.bennu.compose.ui.view.state.ChapterDetailUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.chapter_detail -import bennu.composeapp.generated.resources.no_chunks -import bennu.composeapp.generated.resources.original_text -import bennu.composeapp.generated.resources.chapter_words_characters -import bennu.composeapp.generated.resources.chunk -import bennu.composeapp.generated.resources.chunks -import bennu.composeapp.generated.resources.words_characters -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun ChapterDetailScreen( - activeUserPublicKey: HexKey, - chapterId: String, - chatRoomId: String, - relayHint: String?, - initialChapterDetailUIState: ChapterDetailUIState = ChapterDetailUIState.Loading, - mantraRepository: MantraRepository, - onNavigateBack: () -> Unit, -) { - val chapterDetailViewModel: ChapterDetailViewModel = viewModel( - factory = ChapterDetailViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - chapterId = chapterId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialChapterDetailUIState = initialChapterDetailUIState, - mantraRepository = mantraRepository, - ) - ) - - ScreenStateTransition(chapterDetailViewModel.chapterDetailUIState) { uiState -> - when (val chapterDetailUIState = uiState) { - is ChapterDetailUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - Text(text = chapterDetailUIState.message) - } - } - - is ChapterDetailUIState.Loaded -> { - val chapter = chapterDetailUIState.chapter - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(chapter.name) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - } - ) { innerPadding -> - LazyColumn( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize().padding(MaterialTheme.spacing.space250), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - item { - Text( - text = stringResource(Res.string.chapter_words_characters, chapter.index, chapter.wordCount, chapter.characterCount), - style = MaterialTheme.typography.labelMedium - ) - } - - // Original text (markdown, shown as-is). - item { - Text( - text = stringResource(Res.string.original_text), - style = MaterialTheme.typography.labelMedium - ) - } - item { - Card { - Text( - modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), - text = chapter.originalText, - style = MaterialTheme.typography.bodyMedium - ) - } - } - - item { HorizontalDivider() } - - // Chunks - item { - Text( - text = stringResource(Res.string.chunks, chapterDetailUIState.chunks.size), - style = MaterialTheme.typography.labelMedium - ) - } - if (chapterDetailUIState.chunks.isEmpty()) { - item { Text(stringResource(Res.string.no_chunks)) } - } else { - items( - items = chapterDetailUIState.chunks, - key = { chunk -> chunk.id } - ) { chunk -> - Card { - ListItem( - leadingContent = { - Icon( - Icons.Default.Segment, - contentDescription = "Chunk" - ) - }, - overlineContent = { Text(stringResource(Res.string.chunk, chunk.index)) }, - headlineContent = { Text(chunk.text) }, - supportingContent = { - Text(stringResource(Res.string.words_characters, chunk.wordCount, chunk.characterCount)) - } - ) - } - } - } - } - } - } - - ChapterDetailUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - Spacer(modifier = Modifier.weight(1f)) - Text( - text = stringResource(Res.string.chapter_detail), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - LoadingDataIndicator(fillScreen = false) - Spacer(modifier = Modifier.weight(2f)) - } - } - } - } - - LaunchedEffect(true) { - if (initialChapterDetailUIState == ChapterDetailUIState.Loading) { - chapterDetailViewModel.initiateChapterDetail() - } - } -} - -@ConformancePreviews -@Composable -private fun ChapterDetailScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - ChapterDetailScreen( - activeUserPublicKey = "", - chapterId = "chapterId", - chatRoomId = "chatRoomId", - relayHint = null, - initialChapterDetailUIState = ChapterDetailUIState.Loaded( - chapter = MantraChapter( - id = "chapterId", - artifactVersionId = "versionId", - publicKey = "author", - name = "Chapter 1 — The Beginning", - originalText = "When he was nearly thirteen...\n\nWhen enough years had gone by...", - index = 0, - wordCount = 12, - characterCount = 64, - signature = "", - chatRoomId = "chatRoomId" - ) - ), - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - onNavigateBack = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt index b7ca73fb..b01ee84b 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt @@ -76,7 +76,6 @@ import com.machankura.bennu.compose.database.model.Profile import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.database.model.intermdiate.LocalParticipant import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.MantraRepository import com.machankura.bennu.compose.repository.NostrRepository import com.machankura.bennu.compose.ui.composable.navigation.routes.ProfilePreviewRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.Route @@ -172,7 +171,6 @@ fun ChatRoomDetailScreen( initialChatRoomDetailUIState: ChatRoomDetailUIState = ChatRoomDetailUIState.Loading, nostrRepository: NostrRepository, chatRepository: ChatRepository, - mantraRepository: MantraRepository, onNavigateToRoute: (Route) -> Unit, onPopBackToRoute: (Route) -> Unit, onNavigateBack: () -> Unit, @@ -184,7 +182,6 @@ fun ChatRoomDetailScreen( initialChatRoomDetailUIState = initialChatRoomDetailUIState, nostrRepository = nostrRepository, chatRepository = chatRepository, - mantraRepository = mantraRepository, activeUserPublicKey = activeUserPublicKey ) ) @@ -1423,7 +1420,6 @@ private fun ChatRoomMessagingScreenPreview() { ), nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, onNavigateToRoute = {}, onPopBackToRoute = {}, onNavigateBack = {}, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslateChunkScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslateChunkScreen.kt deleted file mode 100644 index d6c751fb..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslateChunkScreen.kt +++ /dev/null @@ -1,275 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.text.input.rememberTextFieldState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Add -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ImplementationPendingRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.TranslateChunkViewModel -import com.machankura.bennu.compose.ui.view.state.TranslateChunkUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.enter_the_translation_for_this_chunk -import bennu.composeapp.generated.resources.original -import bennu.composeapp.generated.resources.propose_translation -import bennu.composeapp.generated.resources.translate_chunk -import bennu.composeapp.generated.resources.translated_text -import bennu.composeapp.generated.resources.translation -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun TranslateChunkScreen( - activeUserPublicKey: HexKey, - translationChapterId: String, - chunkId: String, - chatRoomId: String, - relayHint: String?, - initialTranslateChunkUIState: TranslateChunkUIState = TranslateChunkUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val translateChunkViewModel: TranslateChunkViewModel = viewModel( - factory = TranslateChunkViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - translationChapterId = translationChapterId, - chunkId = chunkId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialTranslateChunkUIState = initialTranslateChunkUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - ) - - ScreenStateTransition(translateChunkViewModel.translateChunkUIState) { uiState -> - when (val translateChunkUIState = uiState) { - is TranslateChunkUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - Text(text = translateChunkUIState.message) - } - } - - is TranslateChunkUIState.Loaded -> { - val translationFieldState = rememberTextFieldState(translateChunkUIState.existingTranslationText) - - // imePadding: this screen has a text field, and without it the software - // keyboard covers whatever is being typed into. - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.translate_chunk)) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_translation), - icon = { Icon(Icons.Default.Add, contentDescription = "Propose translation") }, - enabled = translateChunkUIState.canSign, - onClick = { - translateChunkViewModel.proposeTranslation( - localChatRoom = translateChunkUIState.localChatRoom, - originalChunk = translateChunkUIState.originalChunk, - translationField = translationFieldState, - onSuccess = { sessionId -> - // Onto the session rather than back to - // the chapter table. Nothing has been - // translated yet -- the chunk is - // translated when enough members sign -- - // so a table still showing it untranslated - // would read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - onFailure = { - onNavigateToRoute.invoke( - ImplementationPendingRoute("Failed translation") - ) - } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier - .padding(innerPadding) - .readableContent() - .fillMaxSize() - .verticalScroll(rememberScrollState()) - .padding(MaterialTheme.spacing.space250), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - if (!translateChunkUIState.canSign) { - Text( - text = "This group has no shared key, so it cannot sign a " + - "translation. Run a shared key ceremony first.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - - Text( - text = stringResource(Res.string.original), - style = MaterialTheme.typography.labelMedium - ) - Card { - Text( - modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), - text = translateChunkUIState.originalChunk.text, - style = MaterialTheme.typography.bodyMedium - ) - } - - Text( - text = stringResource(Res.string.translation), - style = MaterialTheme.typography.labelMedium - ) - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = translationFieldState, - label = { Text(stringResource(Res.string.translated_text)) }, - placeholder = { Text(stringResource(Res.string.enter_the_translation_for_this_chunk)) }, - ) - } - } - } - - TranslateChunkUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - Spacer(modifier = Modifier.weight(1f)) - Text( - text = stringResource(Res.string.translate_chunk), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - LoadingDataIndicator(fillScreen = false) - Spacer(modifier = Modifier.weight(2f)) - } - } - } - } - - LaunchedEffect(true) { - if (initialTranslateChunkUIState == TranslateChunkUIState.Loading) { - translateChunkViewModel.initiateTranslateChunk() - } - } -} - -@ConformancePreviews -@Composable -private fun TranslateChunkScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - TranslateChunkScreen( - activeUserPublicKey = "", - translationChapterId = "translationChapterId", - chunkId = "chunkId", - chatRoomId = "chatRoomId", - relayHint = null, - initialTranslateChunkUIState = TranslateChunkUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "chatRoomId", - userPublicKey = "", - subject = "Message title", - description = "See something. Say somethin", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = null - ), - ), - originalChunk = MantraChunk( - id = "chunkId", - chapterId = "chapterId", - publicKey = "author", - text = "When he was nearly thirteen, my brother Jem got his arm badly broken at the elbow.", - index = 0, - wordCount = 0, - characterCount = 0, - signature = "", - chatRoomId = "chatRoomId" - ), - existingTranslationText = "", - canSign = true - ), - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateToRoute = {}, - onNavigateBack = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslationArtifactVersionDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslationArtifactVersionDetailScreen.kt deleted file mode 100644 index 2e04ac4e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslationArtifactVersionDetailScreen.kt +++ /dev/null @@ -1,310 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Article -import androidx.compose.material.icons.filled.PlaylistAdd -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.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.MantraTranslationArtifactVersion -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.navigation.routes.TranslationChapterRoute -import com.machankura.bennu.compose.ui.composable.widgets.DetailRow -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.TranslationArtifactVersionDetailViewModel -import com.machankura.bennu.compose.ui.view.state.TranslationArtifactVersionDetailUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.chapters -import bennu.composeapp.generated.resources.details -import bennu.composeapp.generated.resources.no_chapters -import bennu.composeapp.generated.resources.propose -import bennu.composeapp.generated.resources.this_group_has_no_shared_key_so_it_cannot -import bennu.composeapp.generated.resources.translation_detail -import bennu.composeapp.generated.resources.chapter -import bennu.composeapp.generated.resources.chunks_translated -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun TranslationArtifactVersionDetailScreen( - activeUserPublicKey: HexKey, - translationArtifactVersionId: String, - chatRoomId: String, - relayHint: String?, - initialTranslationArtifactVersionDetailUIState: TranslationArtifactVersionDetailUIState = TranslationArtifactVersionDetailUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val translationDetailViewModel: TranslationArtifactVersionDetailViewModel = viewModel( - factory = TranslationArtifactVersionDetailViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - translationArtifactVersionId = translationArtifactVersionId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialTranslationArtifactVersionDetailUIState = initialTranslationArtifactVersionDetailUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - ) - - ScreenStateTransition(translationDetailViewModel.translationDetailUIState) { uiState -> - when (val translationDetailUIState = uiState) { - is TranslationArtifactVersionDetailUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - Text(text = translationDetailUIState.message) - } - } - - is TranslationArtifactVersionDetailUIState.Loaded -> { - val translation = translationDetailUIState.translation - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(translation.name) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - } - ) { innerPadding -> - LazyColumn( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize().padding(MaterialTheme.spacing.space250), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - // Chapters the source version has and this translation - // does not. Above the list rather than after it: a chapter - // that is not here is invisible from a list of the ones - // that are. - val localChatRoom = translationDetailUIState.localChatRoom - val missingChapters = translationDetailUIState.missingChapters - - if (missingChapters.isNotEmpty()) { - item { - Card { - ListItem( - leadingContent = { - Icon( - Icons.Default.PlaylistAdd, - contentDescription = "Chapters missing from this translation" - ) - }, - headlineContent = { - Text( - "${missingChapters.size} " + - (if (missingChapters.size == 1) "chapter is" else "chapters are") + - " not in this translation yet" - ) - }, - supportingContent = { - Text( - if (!translationDetailUIState.canSign) { - stringResource(Res.string.this_group_has_no_shared_key_so_it_cannot) - } else { - "They were signed into the artifact after this " + - "translation. Ask the group to add them so they " + - "can be translated." - } - ) - }, - trailingContent = { - TextButton( - enabled = localChatRoom != null && - translationDetailUIState.canSign && - !translationDetailViewModel.isActionPending.value, - onClick = { - if (localChatRoom == null) return@TextButton - - translationDetailViewModel.catchUpMissingChapters( - localChatRoom = localChatRoom, - missingChapters = missingChapters, - onSuccess = { sessionId -> - onNavigateToRoute.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - onFailure = {} - ) - } - ) { - Text(stringResource(Res.string.propose)) - } - } - ) - } - } - - item { HorizontalDivider() } - } - - // Chapters with translation progress - item { - Text( - text = stringResource(Res.string.chapters), - style = MaterialTheme.typography.labelMedium - ) - } - if (translationDetailUIState.chapters.isEmpty()) { - item { Text(stringResource(Res.string.no_chapters)) } - } else { - items( - items = translationDetailUIState.chapters, - key = { progress -> progress.chapter.id } - ) { progress -> - Card( - onClick = { - onNavigateToRoute.invoke( - TranslationChapterRoute( - activeUserPublicKey = activeUserPublicKey, - translationChapterId = progress.chapter.id, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) { - ListItem( - leadingContent = { - Icon( - Icons.Default.Article, - contentDescription = "Chapter" - ) - }, - headlineContent = { Text(stringResource(Res.string.chapter, progress.chapter.index)) }, - supportingContent = { - Text(stringResource(Res.string.chunks_translated, progress.translatedChunks, progress.totalChunks)) - } - ) - } - } - } - - item { HorizontalDivider() } - - // Details - item { - Text( - text = stringResource(Res.string.details), - style = MaterialTheme.typography.labelMedium - ) - } - item { - Card { - DetailRow(label = "Name", value = translation.name) - DetailRow(label = "Dialect", value = translation.dialectId) - DetailRow(label = "Visibility", value = translation.visibility) - DetailRow(label = "License", value = translation.license) - DetailRow(label = "Source version", value = translation.artifactVersionId) - DetailRow(label = "Author", value = translation.publicKey) - DetailRow(label = "Created", value = translation.createdAt.toString()) - } - } - } - } - } - - TranslationArtifactVersionDetailUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - Spacer(modifier = Modifier.weight(1f)) - Text( - text = stringResource(Res.string.translation_detail), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - LoadingDataIndicator(fillScreen = false) - Spacer(modifier = Modifier.weight(2f)) - } - } - } - } - - LaunchedEffect(true) { - if (initialTranslationArtifactVersionDetailUIState == TranslationArtifactVersionDetailUIState.Loading) { - translationDetailViewModel.initiateTranslationArtifactVersionDetail() - } - } -} - -@ConformancePreviews -@Composable -private fun TranslationArtifactVersionDetailScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - TranslationArtifactVersionDetailScreen( - activeUserPublicKey = "", - translationArtifactVersionId = "translationId", - chatRoomId = "chatRoomId", - relayHint = null, - initialTranslationArtifactVersionDetailUIState = TranslationArtifactVersionDetailUIState.Loaded( - translation = MantraTranslationArtifactVersion( - id = "translationId", - publicKey = "author", - artifactVersionId = "versionId", - dialectId = "dialectId", - name = "Sesotho", - visibility = "private", - license = "cc", - signature = "", - chatRoomId = "chatRoomId" - ) - ), - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRoute = {}, - onNavigateBack = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslationChapterScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslationChapterScreen.kt deleted file mode 100644 index 2c1a0b88..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslationChapterScreen.kt +++ /dev/null @@ -1,279 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.IntrinsicSize -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.ChevronRight -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.material3.VerticalDivider -import androidx.compose.material3.minimumInteractiveComponentSize -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.navigation.routes.TranslateChunkRoute -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.TranslationChapterViewModel -import com.machankura.bennu.compose.ui.view.state.ChunkTranslationPair -import com.machankura.bennu.compose.ui.view.state.TranslationChapterUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.chapter_translation -import bennu.composeapp.generated.resources.this_chapter_has_no_chunks -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun TranslationChapterScreen( - activeUserPublicKey: HexKey, - translationChapterId: String, - chatRoomId: String, - relayHint: String?, - initialTranslationChapterUIState: TranslationChapterUIState = TranslationChapterUIState.Loading, - mantraRepository: MantraRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val translationChapterViewModel: TranslationChapterViewModel = viewModel( - factory = TranslationChapterViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - translationChapterId = translationChapterId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialTranslationChapterUIState = initialTranslationChapterUIState, - mantraRepository = mantraRepository, - ) - ) - - ScreenStateTransition(translationChapterViewModel.translationChapterUIState) { uiState -> - when (val translationChapterUIState = uiState) { - is TranslationChapterUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - Text(text = translationChapterUIState.message) - } - } - - is TranslationChapterUIState.Loaded -> { - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.chapter_translation)) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - } - ) { innerPadding -> - LazyColumn( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() - ) { - // Header row: dialect names. - item { - TableRow( - left = { - Text( - text = translationChapterUIState.originalDialectName, - fontWeight = FontWeight.Bold - ) - }, - right = { - Text( - text = translationChapterUIState.translationDialectName, - fontWeight = FontWeight.Bold - ) - }, - ) - HorizontalDivider() - } - - if (translationChapterUIState.rows.isEmpty()) { - item { - Box( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.containerPadding), - contentAlignment = Alignment.Center - ) { - Text(stringResource(Res.string.this_chapter_has_no_chunks)) - } - } - } else { - items( - items = translationChapterUIState.rows, - key = { pair -> pair.originalChunk.id } - ) { pair -> - ChunkTranslationRow( - pair = pair, - onClick = { - onNavigateToRoute.invoke( - TranslateChunkRoute( - activeUserPublicKey = activeUserPublicKey, - translationChapterId = translationChapterId, - chunkId = pair.originalChunk.id, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) - HorizontalDivider() - } - } - } - } - } - - TranslationChapterUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - Spacer(modifier = Modifier.weight(1f)) - Text( - text = stringResource(Res.string.chapter_translation), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - LoadingDataIndicator(fillScreen = false) - Spacer(modifier = Modifier.weight(2f)) - } - } - } - } - - LaunchedEffect(true) { - if (initialTranslationChapterUIState == TranslationChapterUIState.Loading) { - translationChapterViewModel.initiateTranslationChapter() - } - } -} - -@Composable -private fun ChunkTranslationRow( - pair: ChunkTranslationPair, - onClick: () -> Unit, -) { - val translated = pair.translationChunk?.text?.takeIf { it.isNotBlank() } - TableRow( - left = { Text(pair.originalChunk.text) }, - // The whole translation cell opens the chunk translation editor. When - // there is no translation yet, the original text is shown greyed out as - // a placeholder. It stays plain text, laid out like the original cell - // beside it, rather than a button with its own shape and padding. - rightModifier = Modifier.minimumInteractiveComponentSize() - .clickable(onClick = onClick), - right = { - Row(verticalAlignment = Alignment.CenterVertically) { - Text( - modifier = Modifier.weight(1f), - text = translated ?: pair.originalChunk.text, - color = if (translated != null) { - MaterialTheme.colorScheme.onSurface - } else { - MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f) - } - ) - Icon( - Icons.Default.ChevronRight, - contentDescription = "Translate this chunk", - tint = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - }, - ) -} - -@Composable -private fun TableRow( - left: @Composable () -> Unit, - right: @Composable () -> Unit, - rightModifier: Modifier = Modifier, -) { - Row( - modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min) - ) { - Box(modifier = Modifier.weight(1f).padding(MaterialTheme.spacing.space150)) { left() } - VerticalDivider(modifier = Modifier.fillMaxHeight()) - Box(modifier = Modifier.weight(1f).then(rightModifier).padding(MaterialTheme.spacing.space150)) { right() } - } -} - -@ConformancePreviews -@Composable -private fun TranslationChapterScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - TranslationChapterScreen( - activeUserPublicKey = "", - translationChapterId = "translationChapterId", - chatRoomId = "chatRoomId", - relayHint = null, - initialTranslationChapterUIState = TranslationChapterUIState.Loaded( - originalDialectName = "English", - translationDialectName = "Sesotho", - rows = listOf( - ChunkTranslationPair( - originalChunk = sampleChunk("c1", "When he was nearly thirteen, my brother Jem got his arm badly broken."), - translationChunk = null - ), - ChunkTranslationPair( - originalChunk = sampleChunk("c2", "When enough years had gone by to enable us to look back on them..."), - translationChunk = null - ), - ) - ), - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - onNavigateToRoute = {}, - onNavigateBack = {} - ) - } - } -} - -private fun sampleChunk(id: String, text: String) = MantraChunk( - id = id, - chapterId = "chapterId", - publicKey = "author", - text = text, - index = 0, - wordCount = 0, - characterCount = 0, - signature = "", - chatRoomId = "chatRoomId" -) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt index 38a3b0b1..3b9f350b 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt @@ -145,10 +145,6 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch -import com.machankura.bennu.compose.database.repository.DatabaseMantraRepository -import com.machankura.bennu.compose.ui.composable.AddArtifactScreen -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddArtifactRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddDialectRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupNostrProfileRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.AddGroupPostRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute @@ -164,23 +160,8 @@ import fr.acinq.phoenix.managers.NodeParamsManager import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupPostsRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposalListRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddChapterRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddTranslationRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ArtifactDetailRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ChapterDetailRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.TranslateChunkRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.TranslationChapterRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.TranslationArtifactVersionDetailRoute -import com.machankura.bennu.compose.ui.composable.ArtifactDetailScreen -import com.machankura.bennu.compose.ui.composable.AddChapterScreen -import com.machankura.bennu.compose.ui.composable.AddDialectScreen import com.machankura.bennu.compose.ui.composable.FrostSigningScreen import com.machankura.bennu.compose.ui.composable.ProposalListScreen -import com.machankura.bennu.compose.ui.composable.AddTranslationArtifactVersionScreen -import com.machankura.bennu.compose.ui.composable.ChapterDetailScreen -import com.machankura.bennu.compose.ui.composable.TranslateChunkScreen -import com.machankura.bennu.compose.ui.composable.TranslationChapterScreen -import com.machankura.bennu.compose.ui.composable.TranslationArtifactVersionDetailScreen @Composable fun BennuNavHost( @@ -249,12 +230,6 @@ fun BennuNavHost( applicationIOScope ) } - val databaseMantraRepository = remember { - DatabaseMantraRepository( - database = auxDatabaseManager.auxDatabase, - applicationIOScope - ) - } val searchRepository = remember { DatabaseSearchRepository( @@ -1106,7 +1081,6 @@ fun BennuNavHost( relayHint = route.relayHint, nostrRepository = databaseNostrRepository, chatRepository = databaseChatRepository, - mantraRepository = databaseMantraRepository, onNavigateToRoute = { actionRoute -> navController.navigate( route = actionRoute @@ -1169,67 +1143,6 @@ fun BennuNavHost( }, ) } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - AddArtifactScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - nostrRepository = databaseNostrRepository, - chatRepository = databaseChatRepository, - mantraRepository = databaseMantraRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace this add screen so back returns to the group rather - // than to a form whose proposal has already gone out. - navController.navigate( - route = signingRoute - ) { - popUpTo(route) { - inclusive = true - } - } - }, - onNavigateToRoute = { actionRoute -> - navController.navigate( - route = actionRoute - ) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - AddDialectScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - nostrRepository = databaseNostrRepository, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace this add screen so back returns to the group rather - // than to a form whose proposal has already gone out. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateToRoute = { actionRoute -> - navController.navigate( - route = actionRoute - ) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } composable { backStackEntry -> val route = backStackEntry.toRoute() @@ -1475,170 +1388,6 @@ fun BennuNavHost( initialFilter = route.filter ) } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - ArtifactDetailScreen( - activeUserPublicKey = route.activeUserPublicKey, - artifactId = route.artifactId, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - mantraRepository = databaseMantraRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate( - route = actionRoute - ) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - ChapterDetailScreen( - activeUserPublicKey = route.activeUserPublicKey, - chapterId = route.chapterId, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - mantraRepository = databaseMantraRepository, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - TranslationArtifactVersionDetailScreen( - activeUserPublicKey = route.activeUserPublicKey, - translationArtifactVersionId = route.translationArtifactVersionId, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - mantraRepository = databaseMantraRepository, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate( - route = actionRoute - ) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - TranslationChapterScreen( - activeUserPublicKey = route.activeUserPublicKey, - translationChapterId = route.translationChapterId, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - mantraRepository = databaseMantraRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate( - route = actionRoute - ) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - TranslateChunkScreen( - activeUserPublicKey = route.activeUserPublicKey, - translationChapterId = route.translationChapterId, - chunkId = route.chunkId, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - mantraRepository = databaseMantraRepository, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace this editor so back returns to the chapter table - // rather than to a form whose proposal has already gone out. - // The table itself is left alone: nothing is translated until - // the group signs, so there is nothing new for it to show. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateToRoute = { actionRoute -> - navController.navigate(route = actionRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - AddTranslationArtifactVersionScreen( - activeUserPublicKey = route.activeUserPublicKey, - artifactId = route.artifactId, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - mantraRepository = databaseMantraRepository, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace this screen so back returns to the artifact rather - // than to a form whose proposal has already gone out. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateToRoute = { actionRoute -> - navController.navigate( - route = actionRoute - ) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - AddChapterScreen( - activeUserPublicKey = route.activeUserPublicKey, - artifactId = route.artifactId, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - mantraRepository = databaseMantraRepository, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace this add screen so back returns to the artifact - // rather than to a form whose proposal has already gone out. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateToRoute = { actionRoute -> - navController.navigate( - route = actionRoute - ) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddArtifactRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddArtifactRoute.kt deleted file mode 100755 index 5c481e8f..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddArtifactRoute.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class AddArtifactRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddChapterRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddChapterRoute.kt deleted file mode 100644 index c6d2dfa8..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddChapterRoute.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class AddChapterRoute( - val activeUserPublicKey: String, - val artifactId: String, - val chatRoomId: String, - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddDialectRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddDialectRoute.kt deleted file mode 100644 index 6ef108c4..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddDialectRoute.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class AddDialectRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddTranslationRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddTranslationRoute.kt deleted file mode 100644 index ecaaa079..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddTranslationRoute.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class AddTranslationRoute( - val activeUserPublicKey: String, - val artifactId: String, - val chatRoomId: String, - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ArtifactDetailRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ArtifactDetailRoute.kt deleted file mode 100644 index 64d9574e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ArtifactDetailRoute.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class ArtifactDetailRoute( - val activeUserPublicKey: String, - val artifactId: String, - val chatRoomId: String, - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ChapterDetailRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ChapterDetailRoute.kt deleted file mode 100644 index 605e6395..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ChapterDetailRoute.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class ChapterDetailRoute( - val activeUserPublicKey: String, - val chapterId: String, - val chatRoomId: String, - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslateChunkRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslateChunkRoute.kt deleted file mode 100644 index f377c1ae..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslateChunkRoute.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class TranslateChunkRoute( - val activeUserPublicKey: String, - val translationChapterId: String, - val chunkId: String, - val chatRoomId: String, - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslationArtifactVersionDetailRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslationArtifactVersionDetailRoute.kt deleted file mode 100644 index c3150b4c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslationArtifactVersionDetailRoute.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class TranslationArtifactVersionDetailRoute( - val activeUserPublicKey: String, - val translationArtifactVersionId: String, - val chatRoomId: String, - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslationChapterRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslationChapterRoute.kt deleted file mode 100644 index 8133a75b..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslationChapterRoute.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class TranslationChapterRoute( - val activeUserPublicKey: String, - val translationChapterId: String, - val chatRoomId: String, - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/DetailRow.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/DetailRow.kt deleted file mode 100644 index bfb75ffc..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/DetailRow.kt +++ /dev/null @@ -1,14 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.widgets - -import androidx.compose.material3.ListItem -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable - -/** A labelled value row for detail screens (label above, value below). */ -@Composable -fun DetailRow(label: String, value: String) { - ListItem( - overlineContent = { Text(label) }, - headlineContent = { Text(value) } - ) -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddArtifactViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddArtifactViewModel.kt deleted file mode 100644 index bad5507c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddArtifactViewModel.kt +++ /dev/null @@ -1,186 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.foundation.text.input.clearText -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.NostrRepository -import co.touchlab.kermit.Logger -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.view.state.AddArtifactUIState - -class AddArtifactViewModel( - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialAddArtifactUIState: AddArtifactUIState, - val nostrRepository: NostrRepository, - val chatRepository: ChatRepository, - val mantraRepository: MantraRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var addArtifactUIState: AddArtifactUIState by mutableStateOf(initialAddArtifactUIState) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateChatRoomDetail() { - logger.d("compressed (most likely chat room): $chatRoomId") - // Get ChatRoomById - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - addArtifactUIState = if (localChatRoom == null) { - // Initiate new chat... and navigate to new chat... - AddArtifactUIState.Error("Couldn't find the chat room") - } else { - AddArtifactUIState.Loaded( - localChatRoom = localChatRoom, - dialects = mantraRepository.getDialects(localChatRoom.chatRoom.id), - canSign = frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Asks the group to sign an artifact into its library. - * - * The artifact is not created here and does not exist yet. What goes out is - * a proposal to sign it, and the artifact appears -- on every member's - * device at once, authored by this room's own key rather than by whoever - * typed it -- when enough members have signed. That author is the room's id: - * signing runs at the path the room was derived at, so an artifact says - * which library it belongs to simply by being signed. - * - * That is the difference from submitting one. A submission says "I am - * putting this in front of the group" and the group's only recourse - * afterwards is social. A signature is the group saying it, and it takes a - * quorum to say. A library is the group's, so the second is the honest one. - * - * Two events, one session: the artifact and the version it starts life with, - * which a chapter later hangs off. All-or-nothing, which is right here -- - * an artifact with no version is inert, since nothing can attach to it. - */ - fun addArtifact( - localChatRoom: LocalChatRoom, - nameField: TextFieldState, - urlField: TextFieldState, - versionLabelField: TextFieldState, - dialectId: HexKey?, - visibility: String = MantraRepository.DEFAULT_VISIBILITY, - license: String = MantraRepository.DEFAULT_LICENSE, - onSuccess: (sessionId: String) -> Unit, - onFailure: () -> Unit - ) { - val name = nameField.text.toString() - val url = urlField.text.toString() - val versionLabel = versionLabelField.text.toString() - - // An artifact requires an existing source dialect; they are signed into - // existence from the group detail screen, not here. - if (name.isBlank() || url.isBlank() || versionLabel.isBlank() || dialectId.isNullOrBlank()) { - onFailure.invoke() - return - } - - // Guard against double submits from repeated FAB taps. - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - // The label rides on the artifact and the version is signed beside - // it, in the same batch. A first version proposed on its own would - // cost a second quorum for one form, which is why it used to be - // derived on arrival instead; a batch costs one quorum, so the row a - // chapter hangs off can carry the group's signature rather than - // being rebuilt from the artifact by every device that holds it. - val artifactEventTemplate = ArtifactEvent.build( - name = name, - url = url, - visibility = visibility, - license = license, - dialectId = dialectId, - versionLabel = versionLabel, - ) - - val session = runCatching { - frostSigningRepository.proposeSigningBatch( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - lead = artifactEventTemplate, - // The version names the artifact it is of, and that id is a - // hash over the group's key at the room's path -- neither of - // which this screen knows or should. The artifact comes back - // built, and the version is read off the label it declares. - dependents = ArtifactVersionEvent::initialVersionOf - ) - }.onFailure { error -> - logger.e("Failed to propose an artifact for signing", error) - }.getOrNull() - - if (session != null) { - nameField.clearText() - urlField.clearText() - versionLabelField.clearText() - - viewModelScope.launch(Dispatchers.Main) { - onSuccess.invoke(session.id) - } - } else { - viewModelScope.launch(Dispatchers.Main) { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "AddArtifactViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialAddArtifactUIState: AddArtifactUIState = AddArtifactUIState.Loading, - nostrRepository: NostrRepository, - chatRepository: ChatRepository, - mantraRepository: MantraRepository, - frostSigningRepository: FrostSigningRepository - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - AddArtifactViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddArtifactUIState = initialAddArtifactUIState, - nostrRepository = nostrRepository, - chatRepository = chatRepository, - mantraRepository = mantraRepository, - frostSigningRepository = frostSigningRepository - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddChapterViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddChapterViewModel.kt deleted file mode 100644 index 4411786d..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddChapterViewModel.kt +++ /dev/null @@ -1,291 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.foundation.text.input.clearText -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.managers.FrostSigningManager -import com.machankura.bennu.compose.managers.TranslationScaffold -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.text.Markdown -import com.machankura.bennu.compose.ui.view.state.AddChapterUIState - -class AddChapterViewModel( - val artifactId: String, - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialAddChapterUIState: AddChapterUIState, - val mantraRepository: MantraRepository, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var addChapterUIState: AddChapterUIState by mutableStateOf(initialAddChapterUIState) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateAddChapter() { - viewModelScope.launch(Dispatchers.IO) { - val artifact = mantraRepository.getArtifact(artifactId) - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - addChapterUIState = when { - artifact == null -> AddChapterUIState.Error("Couldn't find the artifact") - localChatRoom == null -> AddChapterUIState.Error("Couldn't find the chat room") - else -> AddChapterUIState.Loaded( - localChatRoom = localChatRoom, - artifact = artifact, - // Chapters attach to an artifact version; use the latest one. - artifactVersion = mantraRepository.getArtifactVersions(artifactId).firstOrNull(), - canSign = frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Asks the group to sign a chapter, and every chunk it splits into, in one - * session. - * - * Nothing is created here. What goes out is a proposal to sign the lot, and - * the chapter and its chunks appear on every member's device at once, - * authored by this room's own key rather than by whoever pasted the text, - * when enough members have signed. That author is the room's id: signing - * runs at the path the room was derived at, so a chapter says which group's - * artifact it belongs to simply by being signed. - * - * That is the difference from submitting one. A submission says "I am - * putting this in front of the group" and the group's only recourse - * afterwards is social. A signature is the group saying it, and it takes a - * quorum to say. The text everyone will translate from is the group's, so - * the second is the honest one. - * - * The chunks travel as their own events rather than being split back out of - * the signed chapter on each device, so that each one carries the group's - * signature over its own text -- a translation is of a chunk, and a chunk - * that can be checked on its own is worth more than one that can only be - * checked by re-deriving it. What it costs is [MAX_CHUNKS_PER_CHAPTER]: the - * batch is capped, the chapter takes one of its places, and a chapter with - * more paragraphs than the rest cannot be proposed at all. - */ - fun addChapter( - localChatRoom: LocalChatRoom, - artifactVersion: MantraArtifactVersion, - nameField: TextFieldState, - originalTextField: TextFieldState, - onSuccess: (sessionId: String) -> Unit, - onFailure: () -> Unit - ) { - val name = nameField.text.toString() - val originalText = originalTextField.text.toString() - val paragraphs = Markdown.splitParagraphs(originalText) - - // The cap is the group's, not this screen's, and proposing past it - // throws rather than failing softly. The form says so as it is typed; - // this is the check that has to hold when it does not. - if (name.isBlank() || paragraphs.isEmpty() || paragraphs.size > MAX_CHUNKS_PER_CHAPTER) { - onFailure.invoke() - return - } - - // Guard against double submits from repeated FAB taps. - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - // Where this chapter sits in the version, read now rather than - // derived on arrival: the index is signed into the event, and a - // device applying it cannot recount from a version other members - // may have added to in a different order. The scaffolding proposed - // below is placed at the same one, so a translation chapter agrees - // with the chapter it stands for. - val chapterIndex = mantraRepository.getChaptersForArtifactVersion(artifactVersion.id).size - - val chapterEventTemplate = ChapterEvent.build( - artifactVersionId = artifactVersion.id, - name = name, - originalText = originalText, - index = chapterIndex, - wordCount = Markdown.wordCount(originalText), - characterCount = Markdown.characterCount(originalText), - ) - - val session = runCatching { - frostSigningRepository.proposeSigningBatch( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - lead = chapterEventTemplate, - // A chunk names the chapter it belongs to, and that id is a - // hash over the group's key at the room's path -- neither of - // which this screen knows or should. The chapter comes back - // built, and the chunks are cut from the text it carries. - dependents = ChunkEvent::splitOf - ) - }.onFailure { error -> - logger.e("Failed to propose a chapter for signing", error) - }.getOrNull() - - if (session != null) { - // Before navigating, not after: the route this screen sits on - // is popped on success, which clears this view model and takes - // `viewModelScope` with it. Scaffolding launched afterwards - // would be cancelled somewhere in the middle. - scaffoldIntoTranslations( - localChatRoom = localChatRoom, - artifactVersion = artifactVersion, - chapterIndex = chapterIndex, - chapterSessionId = session.id, - ) - - nameField.clearText() - originalTextField.clearText() - - viewModelScope.launch(Dispatchers.Main) { - onSuccess.invoke(session.id) - } - } else { - viewModelScope.launch(Dispatchers.Main) { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - /** - * Asks the group to scaffold this chapter into every translation of the - * version, in sessions of their own. - * - * Its own session rather than more items on the chapter's, because the two - * would otherwise compete for one batch: a chapter is capped at - * [MAX_CHUNKS_PER_CHAPTER] paragraphs, and every dialect the group works in - * would take one of those places away. How long a chapter may be and how - * many languages it is read in have nothing to do with each other, and a - * shared cap would make the first move whenever somebody else did the - * second. - * - * Sessions run independently -- every message carries the session it - * belongs to, and each mints its own nonce material -- so a second one - * opened here costs the admins another approval and nothing else. - * - * **What a separate session gives up.** A batch is all-or-nothing; two - * sessions are not. If the chapter fails to reach a quorum while this one - * succeeds, these are valid signatures over rows naming a chapter nobody - * has: they fail a foreign key on the way in, are logged by - * `applySignedEvent`, and never become rows. Harmless, and not recoverable - * either -- a re-proposed chapter is a different id -- so the catch-up on - * the translation is what fills the gap afterwards. - * - * The chapter is named as the group will author it: [chapterSessionId]'s - * first item is the unsigned chapter, whose id is the hash its signers are - * putting their shares behind, and it is settled at proposal time rather - * than when the quorum arrives. - * - * Failure here is logged and swallowed. The chapter has already been - * proposed and is the thing that was asked for; losing it because its - * scaffolding could not be opened would be the wrong way round. - */ - private suspend fun scaffoldIntoTranslations( - localChatRoom: LocalChatRoom, - artifactVersion: MantraArtifactVersion, - chapterIndex: Int, - chapterSessionId: String, - ) { - runCatching { - val translations = mantraRepository - .getTranslationsForArtifactVersion(artifactVersion.id) - .ifEmpty { return@runCatching } - - val chapter = frostSigningRepository - .unsignedEvents(frostSigningRepository.getItems(chapterSessionId)) - .firstOrNull() ?: return@runCatching - - // One session per MAX_BATCH_SIZE translations. A group with more - // dialects than a batch holds is not a group this should refuse; - // it is one that answers twice. - translations.chunked(FrostSigningManager.MAX_BATCH_SIZE).forEach { batch -> - frostSigningRepository.proposeSigningBatch( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - events = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = batch.map { it.id }, - chapters = listOf( - TranslationScaffold.SourceChapter( - id = chapter.id, - index = chapterIndex, - ) - ), - createdAt = chapter.createdAt, - ) - ) - } - }.onFailure { error -> - logger.e( - "Proposed the chapter but could not ask for it in this version's translations", - error - ) - } - } - - companion object { - private const val TAG = "AddChapterViewModel" - - /** - * The most paragraphs a chapter can be proposed with. - * - * A chapter is signed together with a chunk per paragraph, and the - * session signs at most [FrostSigningManager.MAX_BATCH_SIZE] events. The - * chapter is one of them, so the paragraphs get the rest. A longer - * chapter has to be split into two, which is a real limit and belongs in - * front of whoever is typing rather than in a failure afterwards. - */ - const val MAX_CHUNKS_PER_CHAPTER: Int = FrostSigningManager.MAX_BATCH_SIZE - 1 - - fun factory( - activeUserPublicKey: HexKey, - artifactId: String, - chatRoomId: String, - relayHint: String?, - initialAddChapterUIState: AddChapterUIState = AddChapterUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - AddChapterViewModel( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifactId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddChapterUIState = initialAddChapterUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddDialectViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddDialectViewModel.kt deleted file mode 100644 index 4e693c7d..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddDialectViewModel.kt +++ /dev/null @@ -1,164 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.foundation.text.input.clearText -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.NostrRepository -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.ui.view.state.AddDialectUIState - -class AddDialectViewModel( - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialAddDialectUIState: AddDialectUIState, - val nostrRepository: NostrRepository, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var addDialectUIState: AddDialectUIState by mutableStateOf(initialAddDialectUIState) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - /** - * Whether this group holds a key it can sign with. - * - * Read before the form is offered: a group without one cannot make a dialect - * this way at all, and a button that always fails is worse than no button. - */ - suspend fun canSign(): Boolean = frostSigningRepository.canSign(chatRoomId) - - fun initiateAddDialect() { - logger.d("compressed (most likely chat room): $chatRoomId") - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - addDialectUIState = if (localChatRoom == null) { - AddDialectUIState.Error("Couldn't find the chat room") - } else { - AddDialectUIState.Loaded( - localChatRoom = localChatRoom, - canSign = frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Asks the group to sign a new dialect into existence. - * - * The dialect is not created here and does not exist yet. What goes out is a - * proposal to sign it, and the dialect appears -- on every member's device at - * once, authored by this room's own key rather than by whoever typed it -- - * when enough members have signed. That author is the room's id: signing runs - * at the path the room was derived at, so a dialect says which room made it - * simply by being signed. - * - * That is the difference from submitting one. A submission says "I am putting - * this in front of the group" and the group's only recourse afterwards is - * social. A signature is the group saying it, and it takes a quorum to say. - */ - fun addDialect( - localChatRoom: LocalChatRoom, - nameField: TextFieldState, - countryField: TextFieldState, - languageField: TextFieldState, - onSuccess: (sessionId: String) -> Unit, - onFailure: () -> Unit - ) { - val name = nameField.text.toString() - val country = countryField.text.toString() - val language = languageField.text.toString() - - if (name.isBlank() || country.isBlank() || language.isBlank()) { - onFailure.invoke() - return - } - - // Guard against double submits from repeated FAB taps. - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - val dialectEventTemplate = DialectEvent.build( - name = name, - country = country, - language = language, - ) - - val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = dialectEventTemplate.kind, - tags = dialectEventTemplate.tags, - content = dialectEventTemplate.content, - ) - }.onFailure { error -> - logger.e("Failed to propose a dialect for signing", error) - }.getOrNull() - - if (session != null) { - nameField.clearText() - countryField.clearText() - languageField.clearText() - - viewModelScope.launch(Dispatchers.Main) { - onSuccess.invoke(session.id) - } - } else { - viewModelScope.launch(Dispatchers.Main) { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "AddDialectViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialAddDialectUIState: AddDialectUIState = AddDialectUIState.Loading, - nostrRepository: NostrRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - AddDialectViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddDialectUIState = initialAddDialectUIState, - nostrRepository = nostrRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddTranslationArtifactVersionViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddTranslationArtifactVersionViewModel.kt deleted file mode 100644 index 0f7693f5..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddTranslationArtifactVersionViewModel.kt +++ /dev/null @@ -1,260 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraDialect -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.managers.FrostSigningManager -import com.machankura.bennu.compose.managers.TranslationScaffold -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.view.state.AddTranslationArtifactVersionUIState - -class AddTranslationArtifactVersionViewModel( - val artifactId: String, - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialAddTranslationArtifactVersionUIState: AddTranslationArtifactVersionUIState, - val mantraRepository: MantraRepository, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var addTranslationArtifactVersionUIState: AddTranslationArtifactVersionUIState by mutableStateOf(initialAddTranslationArtifactVersionUIState) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateAddTranslation() { - viewModelScope.launch(Dispatchers.IO) { - val artifact = mantraRepository.getArtifact(artifactId) - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - // Translations attach to an artifact version; use the latest one. - val artifactVersion = mantraRepository.getArtifactVersions(artifactId).firstOrNull() - - addTranslationArtifactVersionUIState = if (artifact == null || localChatRoom == null) { - AddTranslationArtifactVersionUIState.Error("Couldn't find the artifact") - } else { - AddTranslationArtifactVersionUIState.Loaded( - artifact = artifact, - localChatRoom = localChatRoom, - dialects = mantraRepository.getDialects(chatRoomId), - artifactVersion = artifactVersion, - chapters = artifactVersion - ?.let { mantraRepository.getChaptersForArtifactVersion(it.id) } - .orEmpty(), - canSign = frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Asks the group to sign a translation of the artifact, and a translation - * chapter for every chapter it has, in one session. - * - * Nothing is created here. What goes out is a proposal to sign the lot, and - * the translation and its chapters appear on every member's device at once, - * authored by this room's own key rather than by whoever picked the dialect, - * when enough members have signed. That author is the room's id: signing - * runs at the path the room was derived at, so a translation says which - * group's artifact it belongs to simply by being signed. - * - * That is the difference from submitting one. A submission says "I am - * putting this in front of the group" and the group's only recourse - * afterwards is social. A signature is the group saying it, and it takes a - * quorum to say. A translation is what the group's readers will read the - * artifact as, so the second is the honest one. - * - * The chapters travel with it rather than being scaffolded on each device, - * for the same reason the chapter's chunks do: a translation chapter that - * carries the group's signature can be checked by anybody holding it, and a - * translation with no chapters is one nobody can start translating. What it - * costs is [MAX_CHAPTERS_PER_TRANSLATION]: the batch is capped, the - * translation takes one of its places, and an artifact with more chapters - * than the rest cannot be translated in one session at all. - */ - fun addTranslation( - localChatRoom: LocalChatRoom, - artifact: MantraArtifact, - artifactVersion: MantraArtifactVersion, - dialect: MantraDialect, - chapters: List, - onSuccess: (sessionId: String) -> Unit, - onFailure: () -> Unit - ) { - // Guard against double submits from repeated FAB taps. - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - val translationEventTemplate = TranslationArtifactVersionEvent.build( - artifactVersionId = artifactVersion.id, - dialectId = dialect.id, - // The translation is named after its dialect, and inherits the - // source artifact's visibility and license: it is the same work - // in another tongue, not a new one to license afresh. - name = dialect.name, - visibility = artifact.visibility, - license = artifact.license, - ) - - val session = runCatching { - frostSigningRepository.proposeSigningBatch( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - lead = translationEventTemplate, - // A translation chapter names the translation it belongs to, - // and that id is a hash over the group's key at the room's - // path -- neither of which this screen knows or should. The - // translation comes back built, and the chapters are laid - // out against it. - dependents = { translation -> - TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translation.id), - chapters = chapters.take(MAX_CHAPTERS_PER_TRANSLATION) - .map(TranslationScaffold.SourceChapter::of), - createdAt = translation.createdAt, - ) - } - ) - }.onFailure { error -> - logger.e("Failed to propose a translation for signing", error) - }.getOrNull() - - if (session != null) { - // Before navigating, not after: the route this screen sits on - // is popped on success, which clears this view model and takes - // `viewModelScope` with it. - scaffoldRemainingChapters( - localChatRoom = localChatRoom, - chapters = chapters.drop(MAX_CHAPTERS_PER_TRANSLATION), - translationSessionId = session.id, - ) - - viewModelScope.launch(Dispatchers.Main) { - onSuccess.invoke(session.id) - } - } else { - viewModelScope.launch(Dispatchers.Main) { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - /** - * Asks the group for the chapters that did not fit the translation's own - * session, in sessions of their own. - * - * The alternative was refusing to translate an artifact of more than - * [MAX_CHAPTERS_PER_TRANSLATION] chapters at all, which is a cap on how - * long a book may be dressed up as a cap on a batch. A group with a longer - * one answers more than once instead. - * - * The translation is named as the group will author it: the first item of - * [translationSessionId] is the unsigned translation, and its id is settled - * at proposal time rather than when the quorum arrives. - * - * These carry the same cost as any second session, and the same one the - * chapter side carries: if the translation itself fails to reach a quorum - * these are valid signatures over rows naming a translation nobody has. - * They fail a foreign key on the way in, are logged, and never become rows - * -- and the catch-up on the translation is what fills the gap afterwards. - */ - private suspend fun scaffoldRemainingChapters( - localChatRoom: LocalChatRoom, - chapters: List, - translationSessionId: String, - ) { - if (chapters.isEmpty()) return - - runCatching { - val translation = frostSigningRepository - .unsignedEvents(frostSigningRepository.getItems(translationSessionId)) - .firstOrNull() ?: return@runCatching - - chapters.chunked(FrostSigningManager.MAX_BATCH_SIZE).forEach { batch -> - frostSigningRepository.proposeSigningBatch( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - events = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translation.id), - chapters = batch.map(TranslationScaffold.SourceChapter::of), - createdAt = translation.createdAt, - ) - ) - } - }.onFailure { error -> - logger.e( - "Proposed the translation but could not ask for the chapters past the first session", - error - ) - } - } - - companion object { - private const val TAG = "AddTranslationViewModel" - - /** - * How many chapters ride in the translation's own session. - * - * The translation is signed together with a chapter apiece, and a - * session signs at most [FrostSigningManager.MAX_BATCH_SIZE] events. The - * translation is one of them, so the chapters get the rest. - * - * A cap on the session, not on the work: an artifact with more chapters - * than this is not refused, it is proposed in more than one session. A - * limit whoever is looking at the screen can do nothing about is not a - * limit worth telling them to work around. - */ - const val MAX_CHAPTERS_PER_TRANSLATION: Int = FrostSigningManager.MAX_BATCH_SIZE - 1 - - fun factory( - activeUserPublicKey: HexKey, - artifactId: String, - chatRoomId: String, - relayHint: String?, - initialAddTranslationArtifactVersionUIState: AddTranslationArtifactVersionUIState = AddTranslationArtifactVersionUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - AddTranslationArtifactVersionViewModel( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifactId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddTranslationArtifactVersionUIState = initialAddTranslationArtifactVersionUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ArtifactDetailViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ArtifactDetailViewModel.kt deleted file mode 100644 index 926dd046..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ArtifactDetailViewModel.kt +++ /dev/null @@ -1,74 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.view.state.ArtifactDetailUIState - -class ArtifactDetailViewModel( - val artifactId: String, - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialArtifactDetailUIState: ArtifactDetailUIState, - val mantraRepository: MantraRepository, -): ViewModel() { - - var artifactDetailUIState: ArtifactDetailUIState by mutableStateOf(initialArtifactDetailUIState) - private set - - private val logger = Logger.withTag(TAG) - - fun initiateArtifactDetail() { - logger.d("initiateArtifactDetail: $artifactId") - viewModelScope.launch(Dispatchers.IO) { - val artifact = mantraRepository.getArtifact(artifactId) - - artifactDetailUIState = if (artifact == null) { - ArtifactDetailUIState.Error("Couldn't find the artifact") - } else { - ArtifactDetailUIState.Loaded( - artifact = artifact, - versions = mantraRepository.getArtifactVersions(artifactId), - chapters = mantraRepository.getChaptersForArtifact(artifactId), - translations = mantraRepository.getTranslationsForArtifact(artifactId), - ) - } - } - } - - companion object { - private const val TAG = "ArtifactDetailViewModel" - - fun factory( - activeUserPublicKey: HexKey, - artifactId: String, - chatRoomId: String, - relayHint: String?, - initialArtifactDetailUIState: ArtifactDetailUIState = ArtifactDetailUIState.Loading, - mantraRepository: MantraRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - ArtifactDetailViewModel( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifactId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialArtifactDetailUIState = initialArtifactDetailUIState, - mantraRepository = mantraRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChapterDetailViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChapterDetailViewModel.kt deleted file mode 100644 index 62ad9653..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChapterDetailViewModel.kt +++ /dev/null @@ -1,72 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.view.state.ChapterDetailUIState - -class ChapterDetailViewModel( - val chapterId: String, - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialChapterDetailUIState: ChapterDetailUIState, - val mantraRepository: MantraRepository, -): ViewModel() { - - var chapterDetailUIState: ChapterDetailUIState by mutableStateOf(initialChapterDetailUIState) - private set - - private val logger = Logger.withTag(TAG) - - fun initiateChapterDetail() { - logger.d("initiateChapterDetail: $chapterId") - viewModelScope.launch(Dispatchers.IO) { - val chapter = mantraRepository.getChapter(chapterId) - - chapterDetailUIState = if (chapter == null) { - ChapterDetailUIState.Error("Couldn't find the chapter") - } else { - ChapterDetailUIState.Loaded( - chapter = chapter, - chunks = mantraRepository.getChunksForChapter(chapterId), - ) - } - } - } - - companion object { - private const val TAG = "ChapterDetailViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chapterId: String, - chatRoomId: String, - relayHint: String?, - initialChapterDetailUIState: ChapterDetailUIState = ChapterDetailUIState.Loading, - mantraRepository: MantraRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - ChapterDetailViewModel( - activeUserPublicKey = activeUserPublicKey, - chapterId = chapterId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialChapterDetailUIState = initialChapterDetailUIState, - mantraRepository = mantraRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt index a7f77e8b..ac4802d0 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -13,7 +13,6 @@ import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.MantraRepository import com.machankura.bennu.compose.repository.NostrRepository import com.machankura.bennu.compose.ui.composable.navigation.routes.HomeRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.Route @@ -33,7 +32,6 @@ class ChatRoomDetailViewModel( initialChatRoomDetailUIState: ChatRoomDetailUIState, val nostrRepository: NostrRepository, val chatRepository: ChatRepository, - val mantraRepository: MantraRepository, ): ViewModel() { var chatRoomDetailUIState: ChatRoomDetailUIState by mutableStateOf(initialChatRoomDetailUIState) @@ -219,7 +217,6 @@ class ChatRoomDetailViewModel( initialChatRoomDetailUIState: ChatRoomDetailUIState = ChatRoomDetailUIState.Loading, nostrRepository: NostrRepository, chatRepository: ChatRepository, - mantraRepository: MantraRepository, ): ViewModelProvider.Factory = viewModelFactory { initializer { ChatRoomDetailViewModel( @@ -229,7 +226,6 @@ class ChatRoomDetailViewModel( initialChatRoomDetailUIState = initialChatRoomDetailUIState, nostrRepository = nostrRepository, chatRepository = chatRepository, - mantraRepository = mantraRepository, ) } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslateChunkViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslateChunkViewModel.kt deleted file mode 100644 index 38e195ca..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslateChunkViewModel.kt +++ /dev/null @@ -1,175 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.view.state.TranslateChunkUIState - -class TranslateChunkViewModel( - val translationChapterId: String, - val chunkId: String, - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialTranslateChunkUIState: TranslateChunkUIState, - val mantraRepository: MantraRepository, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var translateChunkUIState: TranslateChunkUIState by mutableStateOf(initialTranslateChunkUIState) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateTranslateChunk() { - viewModelScope.launch(Dispatchers.IO) { - val originalChunk = mantraRepository.getChunk(chunkId) - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - translateChunkUIState = when { - originalChunk == null -> TranslateChunkUIState.Error("Couldn't find the chunk") - localChatRoom == null -> TranslateChunkUIState.Error("Couldn't find the chat room") - else -> TranslateChunkUIState.Loaded( - localChatRoom = localChatRoom, - originalChunk = originalChunk, - // What the group has already signed for this chunk, so a - // retranslation starts from it rather than from nothing. - existingTranslationText = mantraRepository - .getTranslationChunks(translationChapterId) - .firstOrNull { it.chunkId == chunkId } - ?.text - .orEmpty(), - canSign = frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Asks the group to sign this chunk's translation. - * - * The translation is not saved here and does not exist yet. What goes out is - * a proposal to sign it, and the translated chunk appears -- on every - * member's device at once, authored by this room's own key rather than by - * whoever typed it -- when enough members have signed. That author is the - * room's id: signing runs at the path the room was derived at, so a - * translated chunk says which group rendered it simply by being signed. - * - * That is the difference from submitting one. A submission says "I am - * putting this in front of the group" and the group's only recourse - * afterwards is social. A signature is the group saying it, and it takes a - * quorum to say. What a chunk means in another tongue is a claim the group - * is making about somebody else's words, so the second is the honest one. - * - * A retranslation goes the same way: the event carries a different text and - * so a different id, and it replaces the one the group signed before rather - * than editing it -- there is nothing here to edit, since the old text is - * already signed. - */ - fun proposeTranslation( - localChatRoom: LocalChatRoom, - originalChunk: MantraChunk, - translationField: TextFieldState, - onSuccess: (sessionId: String) -> Unit, - onFailure: () -> Unit - ) { - val text = translationField.text.toString() - if (text.isBlank()) { - onFailure.invoke() - return - } - - // Guard against double submits from repeated FAB taps. - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - val translationChunkEventTemplate = TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = originalChunk.id, - // The translation sits where the chunk it translates sits. Read - // off the source rather than counted here: a chapter is - // translated a chunk at a time and in no particular order, so - // counting what is translated so far would number them by who - // got there first. - index = originalChunk.index, - text = text, - ) - - val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = translationChunkEventTemplate.kind, - tags = translationChunkEventTemplate.tags, - content = translationChunkEventTemplate.content, - ) - }.onFailure { error -> - logger.e("Failed to propose a translation for signing", error) - }.getOrNull() - - if (session != null) { - viewModelScope.launch(Dispatchers.Main) { - onSuccess.invoke(session.id) - } - } else { - viewModelScope.launch(Dispatchers.Main) { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "TranslateChunkViewModel" - - fun factory( - activeUserPublicKey: HexKey, - translationChapterId: String, - chunkId: String, - chatRoomId: String, - relayHint: String?, - initialTranslateChunkUIState: TranslateChunkUIState = TranslateChunkUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - TranslateChunkViewModel( - activeUserPublicKey = activeUserPublicKey, - translationChapterId = translationChapterId, - chunkId = chunkId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialTranslateChunkUIState = initialTranslateChunkUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslationArtifactVersionDetailViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslationArtifactVersionDetailViewModel.kt deleted file mode 100644 index 1ef0431c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslationArtifactVersionDetailViewModel.kt +++ /dev/null @@ -1,172 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.utils.TimeUtils -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.managers.FrostSigningManager -import com.machankura.bennu.compose.managers.TranslationScaffold -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.view.state.TranslationChapterProgress -import com.machankura.bennu.compose.ui.view.state.TranslationArtifactVersionDetailUIState - -class TranslationArtifactVersionDetailViewModel( - val translationArtifactVersionId: String, - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialTranslationArtifactVersionDetailUIState: TranslationArtifactVersionDetailUIState, - val mantraRepository: MantraRepository, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var translationDetailUIState: TranslationArtifactVersionDetailUIState by mutableStateOf(initialTranslationArtifactVersionDetailUIState) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateTranslationArtifactVersionDetail() { - logger.d("initiateTranslationArtifactVersionDetail: $translationArtifactVersionId") - viewModelScope.launch(Dispatchers.IO) { - val translation = mantraRepository.getTranslation(translationArtifactVersionId) - - translationDetailUIState = if (translation == null) { - TranslationArtifactVersionDetailUIState.Error("Couldn't find the translation") - } else { - val translationChapters = mantraRepository.getTranslationChapters(translationArtifactVersionId) - val chapters = translationChapters.map { chapter -> - val chunks = mantraRepository.getTranslationChunks(chapter.id) - TranslationChapterProgress( - chapter = chapter, - totalChunks = chunks.size, - translatedChunks = chunks.count { it.text.isNotBlank() }, - ) - } - - TranslationArtifactVersionDetailUIState.Loaded( - translation = translation, - chapters = chapters, - localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId), - missingChapters = TranslationScaffold.chaptersMissingFrom( - translationChapters = translationChapters, - sourceChapters = mantraRepository - .getChaptersForArtifactVersion(translation.artifactVersionId), - ), - canSign = frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Asks the group to put the chapters this translation is missing into it. - * - * The scaffolding a chapter is signed with covers the translations that - * existed when it was proposed, and the scaffolding a translation is signed - * with covers the chapters that existed when *it* was proposed. Two things - * proposed at the same moment see neither the other, and a session that - * fails to reach a quorum leaves nothing behind to try again with. Neither - * is a bug that can be designed out of a snapshot taken at proposal time -- - * so this is the pass that reconciles them, run when somebody notices. - * - * It proposes only what is missing, matched on the source chapter each - * translation chapter names, so running it on a translation that is already - * complete proposes nothing rather than a second copy of everything. - */ - fun catchUpMissingChapters( - localChatRoom: LocalChatRoom, - missingChapters: List, - onSuccess: (sessionId: String) -> Unit, - onFailure: () -> Unit - ) { - if (missingChapters.isEmpty()) { - onFailure.invoke() - return - } - - // Guard against double submits from repeated taps. - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - // One timestamp for the lot, so a catch-up reads as the one act it - // is rather than as chapters that happen to share a minute. - val createdAt = TimeUtils.now() - - val sessions = runCatching { - // One session per MAX_BATCH_SIZE chapters. A translation far - // enough behind to need more than a batch holds is not one to - // refuse; it is one the group answers for more than once. - missingChapters.chunked(FrostSigningManager.MAX_BATCH_SIZE).mapNotNull { batch -> - frostSigningRepository.proposeSigningBatch( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - events = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translationArtifactVersionId), - chapters = batch.map(TranslationScaffold.SourceChapter::of), - createdAt = createdAt, - ) - ) - } - }.onFailure { error -> - logger.e("Failed to propose this translation's missing chapters", error) - }.getOrNull().orEmpty() - - // The first, because it is the one that opened; the rest are in the - // room's session list beside it. - val session = sessions.firstOrNull() - - viewModelScope.launch(Dispatchers.Main) { - if (session != null) onSuccess.invoke(session.id) else onFailure.invoke() - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "TranslationArtifactVersionDetailViewModel" - - fun factory( - activeUserPublicKey: HexKey, - translationArtifactVersionId: String, - chatRoomId: String, - relayHint: String?, - initialTranslationArtifactVersionDetailUIState: TranslationArtifactVersionDetailUIState = TranslationArtifactVersionDetailUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - TranslationArtifactVersionDetailViewModel( - activeUserPublicKey = activeUserPublicKey, - translationArtifactVersionId = translationArtifactVersionId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialTranslationArtifactVersionDetailUIState = initialTranslationArtifactVersionDetailUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslationChapterViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslationChapterViewModel.kt deleted file mode 100644 index 8a61891e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslationChapterViewModel.kt +++ /dev/null @@ -1,98 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.view.state.ChunkTranslationPair -import com.machankura.bennu.compose.ui.view.state.TranslationChapterUIState - -class TranslationChapterViewModel( - val translationChapterId: String, - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialTranslationChapterUIState: TranslationChapterUIState, - val mantraRepository: MantraRepository, -): ViewModel() { - - var translationChapterUIState: TranslationChapterUIState by mutableStateOf(initialTranslationChapterUIState) - private set - - private val logger = Logger.withTag(TAG) - - fun initiateTranslationChapter() { - logger.d("initiateTranslationChapter: $translationChapterId") - viewModelScope.launch(Dispatchers.IO) { - val translationChapter = mantraRepository.getTranslationChapter(translationChapterId) - val sourceChapter = translationChapter?.let { mantraRepository.getChapter(it.chapterId) } - - translationChapterUIState = if (translationChapter == null || sourceChapter == null) { - TranslationChapterUIState.Error("Couldn't find the translation chapter") - } else { - // Original dialect: source chapter -> version -> artifact -> dialect. - val originalDialectName = mantraRepository.getArtifactVersion(sourceChapter.artifactVersionId) - ?.let { mantraRepository.getArtifact(it.artifactId) } - ?.let { mantraRepository.getDialect(it.dialectId) } - ?.name ?: "Original" - - // Translation dialect: translation version -> dialect. - val translationDialectName = mantraRepository.getTranslation(translationChapter.translationArtifactVersionId) - ?.let { mantraRepository.getDialect(it.dialectId) } - ?.name ?: "Translation" - - // Pair each original chunk with its translation chunk (by chunkId). - val translationChunksByChunkId = mantraRepository - .getTranslationChunks(translationChapter.id) - .associateBy { it.chunkId } - - val rows = mantraRepository.getChunksForChapter(sourceChapter.id).map { originalChunk -> - ChunkTranslationPair( - originalChunk = originalChunk, - translationChunk = translationChunksByChunkId[originalChunk.id], - ) - } - - TranslationChapterUIState.Loaded( - originalDialectName = originalDialectName, - translationDialectName = translationDialectName, - rows = rows, - ) - } - } - } - - companion object { - private const val TAG = "TranslationChapterViewModel" - - fun factory( - activeUserPublicKey: HexKey, - translationChapterId: String, - chatRoomId: String, - relayHint: String?, - initialTranslationChapterUIState: TranslationChapterUIState = TranslationChapterUIState.Loading, - mantraRepository: MantraRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - TranslationChapterViewModel( - activeUserPublicKey = activeUserPublicKey, - translationChapterId = translationChapterId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialTranslationChapterUIState = initialTranslationChapterUIState, - mantraRepository = mantraRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddArtifactUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddArtifactUIState.kt deleted file mode 100755 index 4de694a1..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddArtifactUIState.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraDialect -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom - -sealed interface AddArtifactUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - val dialects: List = emptyList(), - - /** - * Whether the group holds a shared key. An artifact is signed into - * existence now rather than submitted, so a group without one cannot - * add one here at all. - */ - val canSign: Boolean = false, - ): AddArtifactUIState - - data class Error( - val message: String - ): AddArtifactUIState - - data object Loading: AddArtifactUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddChapterUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddChapterUIState.kt deleted file mode 100644 index 89ff2ca2..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddChapterUIState.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom - -sealed interface AddChapterUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - val artifact: MantraArtifact, - - /** - * The version the chapter would attach to: the artifact's latest. - * - * Null on an artifact that has none, which is one nothing can be added - * to -- a chapter hangs off a version rather than off an artifact. - */ - val artifactVersion: MantraArtifactVersion? = null, - - /** - * Whether the group holds a shared key. A chapter is signed into - * existence now rather than submitted, so a group without one cannot - * add one here at all. - */ - val canSign: Boolean = false, - ): AddChapterUIState - - data class Error( - val message: String - ): AddChapterUIState - - data object Loading: AddChapterUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddDialectUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddDialectUIState.kt deleted file mode 100644 index 21951d3a..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddDialectUIState.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom - -sealed interface AddDialectUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - - /** - * Whether the group holds a shared key. A dialect is signed into - * existence now rather than submitted, so a group without one cannot - * make one here at all. - */ - val canSign: Boolean = false, - ): AddDialectUIState - - data class Error( - val message: String - ): AddDialectUIState - - data object Loading: AddDialectUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddTranslationArtifactVersionUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddTranslationArtifactVersionUIState.kt deleted file mode 100644 index 36edc1c9..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddTranslationArtifactVersionUIState.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraDialect -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom - -sealed interface AddTranslationArtifactVersionUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - val artifact: MantraArtifact, - - /** - * The dialects this room has signed into existence. A translation is - * into one of them and only one of them: an invented dialect is a - * dialect nobody agreed to, and the room already has a screen for - * asking the group for a new one. - */ - val dialects: List = emptyList(), - - /** - * The version being translated: the artifact's latest. - * - * Null on an artifact that has none, which is one there is nothing to - * translate -- a translation is of a version rather than of an artifact. - */ - val artifactVersion: MantraArtifactVersion? = null, - - /** - * The chapters of that version, which the translation is laid out - * against: a translation chapter each, signed in the same session. - * - * Held here rather than re-read when proposing, so that the count the - * form shows is the count the group is asked to sign. - */ - val chapters: List = emptyList(), - - /** - * Whether the group holds a shared key. A translation is signed into - * existence now rather than submitted, so a group without one cannot - * start one here at all. - */ - val canSign: Boolean = false, - ): AddTranslationArtifactVersionUIState - - data class Error( - val message: String - ): AddTranslationArtifactVersionUIState - - data object Loading: AddTranslationArtifactVersionUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ArtifactDetailUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ArtifactDetailUIState.kt deleted file mode 100644 index 468ed2d2..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ArtifactDetailUIState.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraTranslationArtifactVersion - -sealed interface ArtifactDetailUIState { - data class Loaded( - val artifact: MantraArtifact, - val versions: List = emptyList(), - val chapters: List = emptyList(), - val translations: List = emptyList(), - ): ArtifactDetailUIState - - data class Error( - val message: String - ): ArtifactDetailUIState - - data object Loading: ArtifactDetailUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChapterDetailUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChapterDetailUIState.kt deleted file mode 100644 index 33b9d74b..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChapterDetailUIState.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraChunk - -sealed interface ChapterDetailUIState { - data class Loaded( - val chapter: MantraChapter, - val chunks: List = emptyList(), - ): ChapterDetailUIState - - data class Error( - val message: String - ): ChapterDetailUIState - - data object Loading: ChapterDetailUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslateChunkUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslateChunkUIState.kt deleted file mode 100644 index b6281d6c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslateChunkUIState.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom - -sealed interface TranslateChunkUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - val originalChunk: MantraChunk, - val existingTranslationText: String = "", - - /** - * Whether the group holds a shared key. A translation is signed into - * existence now rather than saved, so a group without one cannot - * translate a chunk here at all. - */ - val canSign: Boolean = false, - ): TranslateChunkUIState - - data class Error( - val message: String - ): TranslateChunkUIState - - data object Loading: TranslateChunkUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslationArtifactVersionDetailUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslationArtifactVersionDetailUIState.kt deleted file mode 100644 index 3d67b44a..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslationArtifactVersionDetailUIState.kt +++ /dev/null @@ -1,48 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraTranslationArtifactVersion -import com.machankura.bennu.compose.database.model.MantraTranslationChapter -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom - -/** A translation chapter with how many of its chunks have been translated. */ -data class TranslationChapterProgress( - val chapter: MantraTranslationChapter, - val totalChunks: Int, - val translatedChunks: Int, -) - -sealed interface TranslationArtifactVersionDetailUIState { - data class Loaded( - val translation: MantraTranslationArtifactVersion, - val chapters: List = emptyList(), - - /** - * The room this translation belongs to, which is who would sign the - * chapters it is missing. Null when it cannot be read, which is a - * translation nothing can be proposed for. - */ - val localChatRoom: LocalChatRoom? = null, - - /** - * Chapters of the source version this translation has nothing for. - * - * A translation covers the chapters that existed when it was proposed, - * and a chapter signed afterwards is scaffolded into it by a session of - * that chapter's own -- which the two can miss, by being proposed at the - * same moment or by one of them not reaching a quorum. This is what is - * left over when they do, and it is shown rather than inferred because - * a chapter nobody can translate is invisible from the translation. - */ - val missingChapters: List = emptyList(), - - /** Whether the group holds a shared key, without which nothing can be proposed. */ - val canSign: Boolean = false, - ): TranslationArtifactVersionDetailUIState - - data class Error( - val message: String - ): TranslationArtifactVersionDetailUIState - - data object Loading: TranslationArtifactVersionDetailUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslationChapterUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslationChapterUIState.kt deleted file mode 100644 index 0f2b8a08..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslationChapterUIState.kt +++ /dev/null @@ -1,28 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.database.model.MantraTranslationChunk - -/** - * An original chunk paired with its translation chunk. [translationChunk] is - * null (or has blank text) when the chunk hasn't been translated yet, in which - * case the UI shows the original text as a greyed-out placeholder. - */ -data class ChunkTranslationPair( - val originalChunk: MantraChunk, - val translationChunk: MantraTranslationChunk?, -) - -sealed interface TranslationChapterUIState { - data class Loaded( - val originalDialectName: String, - val translationDialectName: String, - val rows: List = emptyList(), - ): TranslationChapterUIState - - data class Error( - val message: String - ): TranslationChapterUIState - - data object Loading: TranslationChapterUIState -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/TranslationScaffoldTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/TranslationScaffoldTest.kt deleted file mode 100644 index 2290545f..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/TranslationScaffoldTest.kt +++ /dev/null @@ -1,183 +0,0 @@ -package com.machankura.bennu.compose.managers - -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraTranslationChapter -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.ChapterIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.IndexTag -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationArtifactVersionIdTag - -/** - * The join between a translation and the chapters it is of, as a pure function. - * - * Both ends arrive on their own schedule, so this is built from three - * directions -- a translation being proposed, a chapter being proposed, and a - * catch-up filling in what the two missed. What it must not do is disagree with - * itself about what a translation covers depending on which direction it was - * built from. - */ -class TranslationScaffoldTest { - - private val translationA = "a".repeat(64) - private val translationB = "b".repeat(64) - - private fun sourceChapter(index: Int, id: String = "c$index".padEnd(64, 'f')) = MantraChapter( - id = id, - artifactVersionId = "v".repeat(64), - publicKey = "p".repeat(64), - name = "Chapter ${index + 1}", - originalText = "Paragraph.", - index = index, - wordCount = 1, - characterCount = 10, - signature = "", - chatRoomId = "r".repeat(64), - ) - - private fun translationChapterFor(chapter: MantraChapter, translationId: String) = - MantraTranslationChapter( - id = "t${chapter.id}".take(64), - publicKey = "p".repeat(64), - chapterId = chapter.id, - translationArtifactVersionId = translationId, - index = chapter.index, - signature = "", - chatRoomId = "r".repeat(64), - ) - - private fun parse(templates: List>) = - templates.map { template -> - Triple( - template.tags.firstNotNullOfOrNull(TranslationArtifactVersionIdTag::parse)?.ref?.eventId, - template.tags.firstNotNullOfOrNull(ChapterIdTag::parse)?.ref?.eventId, - template.tags.firstNotNullOfOrNull(IndexTag::parse)?.index, - ) - } - - @Test - fun `a translation's chapters stay together and in reading order`() { - val chapters = (0..2).map(::sourceChapter) - - val templates = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translationA, translationB), - chapters = chapters.map(TranslationScaffold.SourceChapter::of), - createdAt = 1_000, - ) - - // Item order is the order a session signs and applies in, so it is - // fixed here rather than left to a caller. Translations outer, chapters - // inner: one translation's chapters are contiguous and in order. - assertEquals( - listOf( - Triple(translationA, chapters[0].id, 0), - Triple(translationA, chapters[1].id, 1), - Triple(translationA, chapters[2].id, 2), - Triple(translationB, chapters[0].id, 0), - Triple(translationB, chapters[1].id, 1), - Triple(translationB, chapters[2].id, 2), - ), - parse(templates) - ) - } - - @Test - fun `a chapter proposed on its own is scaffolded into every translation`() { - // The other direction: one chapter, every existing translation. This is - // what a chapter's own scaffolding session carries. - val templates = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translationA, translationB), - chapters = listOf(TranslationScaffold.SourceChapter(id = "z".repeat(64), index = 7)), - createdAt = 1_000, - ) - - assertEquals( - listOf( - Triple(translationA, "z".repeat(64), 7), - Triple(translationB, "z".repeat(64), 7), - ), - parse(templates) - ) - } - - @Test - fun `a catch-up keeps each chapter's own position not the position in the gap`() { - val chapters = (0..5).map(::sourceChapter) - - // A catch-up proposes a subset, and the subset is not contiguous. - // Counting the list would renumber chapters 3 and 5 as 1 and 2, which - // is a translation that reads in a different order than the work. - val templates = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translationA), - chapters = listOf(chapters[3], chapters[5]).map(TranslationScaffold.SourceChapter::of), - createdAt = 1_000, - ) - - assertEquals(listOf(3, 5), parse(templates).map { it.third }) - } - - @Test - fun `the whole scaffolding carries one timestamp`() { - val templates = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translationA, translationB), - chapters = (0..2).map(::sourceChapter).map(TranslationScaffold.SourceChapter::of), - createdAt = 4_242, - ) - - // Read once by the caller rather than per template, so a scaffolding - // proposed as one act reads as one. - assertEquals(listOf(4_242L), templates.map { it.createdAt }.distinct()) - } - - @Test - fun `nothing to scaffold when there is nothing on one side`() { - assertTrue( - TranslationScaffold.chaptersOf( - translationArtifactVersionIds = emptyList(), - chapters = listOf(TranslationScaffold.SourceChapter("z".repeat(64), 0)), - createdAt = 1_000, - ).isEmpty() - ) - - assertTrue( - TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translationA), - chapters = emptyList(), - createdAt = 1_000, - ).isEmpty() - ) - } - - @Test - fun `what is missing is matched on the chapter named not on how many there are`() { - val chapters = (0..3).map(::sourceChapter) - - // Chapter 1 never landed but chapter 2 did, which a count would read as - // "the last one is missing" and scaffold the wrong chapter. - val missing = TranslationScaffold.chaptersMissingFrom( - translationChapters = listOf(chapters[0], chapters[2]).map { - translationChapterFor(it, translationA) - }, - sourceChapters = chapters, - ) - - assertEquals(listOf(chapters[1].id, chapters[3].id), missing.map { it.id }) - } - - @Test - fun `a translation that is already complete is missing nothing`() { - val chapters = (0..2).map(::sourceChapter) - - // So that running a catch-up twice proposes nothing the second time, - // rather than a second copy of every chapter under fresh ids. - assertEquals( - emptyList(), - TranslationScaffold.chaptersMissingFrom( - translationChapters = chapters.map { translationChapterFor(it, translationA) }, - sourceChapters = chapters, - ) - ) - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/TranslationBatchProposalJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/TranslationBatchProposalJvmTest.kt deleted file mode 100644 index c4b362d7..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/TranslationBatchProposalJvmTest.kt +++ /dev/null @@ -1,473 +0,0 @@ -package com.machankura.bennu.compose.managers - -import androidx.room3.Room -import com.vitorpamplona.quartz.nip01Core.core.Event -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertNotEquals -import kotlin.test.assertTrue -import kotlinx.coroutines.runBlocking -import com.machankura.bennu.compose.database.BennuDatabase -import com.machankura.bennu.compose.database.builder.getRoomDatabase -import com.machankura.bennu.compose.database.model.ChatMessage -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.DkgParticipantMessage -import com.machankura.bennu.compose.database.model.DkgSession -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.database.model.Profile -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.database.model.types.DkgRitualStage -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.text.Markdown -import com.machankura.bennu.compose.ui.view.model.AddChapterViewModel -import com.machankura.bennu.compose.ui.view.model.AddTranslationArtifactVersionViewModel - -/** - * What a translation proposal actually puts in front of the group. - * - * The same sharp edge `ChapterBatchProposalJvmTest` covers for a chapter and - * its chunks, one level up: a translation chapter carries the id of the - * translation it belongs to, and that id does not exist until the proposal - * authors the translation under the group's key at the room's derivation path. - * Both are resolved inside `proposeSigningBatch` and neither is knowable to the - * caller, which is why the chapters are built from what it hands back. - * - * If that came apart, the translation would still be signed and every chapter - * would still verify -- against a translation id nobody has. They would fail a - * foreign key on the way in and the translation would simply arrive with no - * chapters, which is a translation nobody can start. - */ -class TranslationBatchProposalJvmTest { - private val participants = 3 - private val threshold = 2 - - /** Stands in for a completed ceremony; the test is about the proposal, not the DKG. */ - private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - private val thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex() - - /** The admin room: the group's key walked to the admin path, which is its id. */ - private val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) - - private val ceremonyId = "ceremony".padEnd(64, '0') - private val members = listOf("a", "b", "c").map { it.repeat(64) } - private val hostKeys = listOf("2a", "2b", "2c").map { it.padEnd(66, '0') } - - private val proposer = members.first() - private val artifactVersionId = "b".repeat(64) - private val dialectId = "d".repeat(64) - - private lateinit var db: BennuDatabase - private lateinit var room: LocalChatRoom - - @AfterTest - fun closeDatabase() { - if (::db.isInitialized) db.close() - } - - /** The proposer's device: a room it can sign in, and the share to sign with. */ - private suspend fun openDevice() { - db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - - // Profile hangs off a nostr event, and a room off a profile. Neither is - // anything this test is about; they are the foreign keys in the way. - val nostrEventId = "e$proposer".take(64) - db.nostrEventDao().upsert( - NostrEvent( - id = nostrEventId, - pubKey = proposer, - kind = 0, - tags = emptyArray(), - content = "{}", - sig = "0".repeat(128) - ) - ) - db.profileDao().upsert(Profile(publicKey = proposer, nostrEventId = nostrEventId)) - - val chatRoom = ChatRoom( - id = roomId, - userPublicKey = proposer, - subject = "#Ekklesia", - description = SharedKeyDerivation.describe("Admins of the group."), - mlsGroupState = null - ) - db.chatRoomDao().upsert(chatRoom) - - db.dkgSessionDao().upsert( - DkgSession( - id = ceremonyId, - chatRoomId = roomId, - coordinatorPublicKey = proposer, - userPublicKey = proposer, - threshold = threshold, - participantCount = participants, - stage = DkgRitualStage.COMPLETE, - hostPublicKey = hostKeys[0], - round1Random = "1".repeat(64), - round2AuxRandom = "2".repeat(64), - thresholdPublicKey = thresholdPublicKey, - secretShare = keyMaterial.secretShares[0].value.toHex(), - publicShares = keyMaterial.publicShares.joinToString(",") { it.value.toHex() } - ) - ) - - members.forEachIndexed { index, member -> - db.dkgSessionDao().upsert( - DkgParticipantMessage( - sessionId = ceremonyId, - participantPublicKey = member, - kind = DkgRitualEvents.HOST_KEY, - payload = hostKeys[index] - ) - ) - } - - room = LocalChatRoom(chatRoom = chatRoom) - } - - /** - * The source chapters, as the artifact already holds them. Only the id and - * the position travel into the translation, so nothing else is furnished. - */ - private fun sourceChapters(count: Int): List = (0 until count).map { index -> - MantraChapter( - id = "c$index".padEnd(64, 'f'), - artifactVersionId = artifactVersionId, - publicKey = roomId, - name = "Chapter ${index + 1}", - originalText = "Paragraph ${index + 1}.", - index = index, - wordCount = 2, - characterCount = 13, - signature = "0".repeat(128), - chatRoomId = roomId - ) - } - - private val translationTemplate = TranslationArtifactVersionEvent.build( - artifactVersionId = artifactVersionId, - dialectId = dialectId, - name = "Sesotho", - visibility = "private", - license = "cc", - ) - - /** Exactly what `AddTranslationArtifactVersionViewModel.addTranslation` proposes. */ - private suspend fun proposeTranslation(chapters: List) = - FrostSigningManager.proposeSigningBatch( - database = db, - localChatRoom = room, - userPublicKey = proposer, - lead = translationTemplate, - dependents = { translation -> - TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translation.id), - chapters = chapters.map(TranslationScaffold.SourceChapter::of), - createdAt = translation.createdAt, - ) - } - ) - - private suspend fun itemEvents(sessionId: String): List = - db.frostSigningSessionDao().getItems(sessionId).map { Event.fromJson(it.unsignedEventJson) } - - @Test - fun `the translation leads the batch and its chapters follow`() = runBlocking { - openDevice() - - val events = itemEvents(proposeTranslation(sourceChapters(3)).id) - - // Item order is apply order, and a translation chapter row whose - // translation does not exist yet is a foreign key violation. The - // translation has to be first. - assertEquals(4, events.size) - assertEquals(TranslationArtifactVersionEvent.KIND, events.first().kind) - assertTrue(events.drop(1).all { it.kind == TranslationChapterEvent.KIND }) - } - - @Test - fun `every chapter names the translation as the group will author it`() = runBlocking { - openDevice() - - val events = itemEvents(proposeTranslation(sourceChapters(3)).id) - val translation = events.first() - - // The claim the whole `lead`/`dependents` form exists for. The id here is - // a hash over the group's key at the room's path; a caller that built the - // chapters before proposing could not have known it. - val chapters = events.drop(1).map { - TranslationChapterEvent(it.id, it.pubKey, it.createdAt, it.tags, it.content, it.sig) - } - - assertTrue(chapters.all { it.translationArtifactVersionId() == translation.id }) - } - - @Test - fun `each chapter keeps the source chapter it stands in for, and its place`() = runBlocking { - openDevice() - - val source = sourceChapters(3) - val events = itemEvents(proposeTranslation(source).id) - val chapters = events.drop(1).map { - TranslationChapterEvent(it.id, it.pubKey, it.createdAt, it.tags, it.content, it.sig) - } - - // A translation chapter is only ever a place to hang translated chunks - // off the right source chapter, in the right order. Lose either and the - // translation reads as some other book. - assertEquals(source.map { it.id }, chapters.map { it.chapterId() }) - assertEquals(source.map { it.index }, chapters.map { it.index() }) - } - - @Test - fun `the whole batch is stamped and authored as one act by the room`() = runBlocking { - openDevice() - - val events = itemEvents(proposeTranslation(sourceChapters(3)).id) - - // Signing runs at the path the room was derived at, so the author of - // every item is the room's own id -- chapters included, which is what - // lets one be checked without being told which key to expect. - assertTrue(events.all { it.pubKey == roomId }) - assertTrue(events.none { it.pubKey == proposer }) - - // And they carry the translation's timestamp rather than each reading - // the clock, so the batch is one act rather than events that happen to - // share a session. - assertEquals(listOf(events.first().createdAt), events.map { it.createdAt }.distinct()) - } - - @Test - fun `an artifact of the most chapters allowed still proposes`() = runBlocking { - openDevice() - - val events = itemEvents( - proposeTranslation(sourceChapters(FrostSigningManager.MAX_BATCH_SIZE - 1)).id - ) - - // The arithmetic the form is built on: the translation takes one of the - // batch's places and the chapters get the rest. If this stopped being - // true, the screen would offer a translation the session then refuses. - assertEquals( - FrostSigningManager.MAX_BATCH_SIZE, - AddTranslationArtifactVersionViewModel.MAX_CHAPTERS_PER_TRANSLATION + 1 - ) - assertEquals(FrostSigningManager.MAX_BATCH_SIZE, events.size) - } - - /** Exactly what `AddChapterViewModel.addChapter` proposes: the chapter, then its chunks. */ - private suspend fun proposeChapter(paragraphs: Int, index: Int = 0) = - FrostSigningManager.proposeSigningBatch( - database = db, - localChatRoom = room, - userPublicKey = proposer, - lead = (1..paragraphs).joinToString("\n\n") { "Paragraph $it." }.let { text -> - ChapterEvent.build( - artifactVersionId = artifactVersionId, - name = "Chapter ${index + 1}", - originalText = text, - index = index, - wordCount = Markdown.wordCount(text), - characterCount = Markdown.characterCount(text), - ) - }, - dependents = ChunkEvent::splitOf - ) - - /** And what it proposes straight afterwards: that chapter, into every translation. */ - private suspend fun proposeScaffolding(chapter: Event, index: Int, translationIds: List) = - FrostSigningManager.proposeSigningBatch( - database = db, - localChatRoom = room, - userPublicKey = proposer, - events = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = translationIds, - chapters = listOf(TranslationScaffold.SourceChapter(id = chapter.id, index = index)), - createdAt = chapter.createdAt, - ) - ) - - @Test - fun `a chapter's scaffolding runs beside it as a session of its own`() = runBlocking { - openDevice() - - val translationIds = listOf("1".repeat(64), "2".repeat(64), "3".repeat(64)) - - val chapterSession = proposeChapter(paragraphs = 2) - val chapter = itemEvents(chapterSession.id).first() - val scaffoldSession = proposeScaffolding(chapter, index = 0, translationIds = translationIds) - - // Two live sessions in one room, which is the whole point: every FROST - // message carries the session it belongs to, so neither is the room's - // "current" one and nothing had to be finished before the second - // opened. - assertNotEquals(chapterSession.id, scaffoldSession.id) - assertEquals(2, db.frostSigningSessionDao().getSessionsForChatRoom(roomId).size) - - // The chapter's batch is what it would have been with no translations - // at all: the chapter and a chunk per paragraph, and nothing else. - val chapterItems = itemEvents(chapterSession.id) - assertEquals(3, chapterItems.size) - assertEquals(ChapterEvent.KIND, chapterItems.first().kind) - assertTrue(chapterItems.drop(1).all { it.kind == ChunkEvent.KIND }) - - // And the scaffolding names that chapter, in every translation. - val scaffolded = itemEvents(scaffoldSession.id).map { - TranslationChapterEvent(it.id, it.pubKey, it.createdAt, it.tags, it.content, it.sig) - } - assertEquals(translationIds, scaffolded.map { it.translationArtifactVersionId() }) - assertTrue(scaffolded.all { it.chapterId() == chapter.id }) - } - - @Test - fun `each session's transcript lines name it, and never the other`() = runBlocking { - openDevice() - - val chapterSession = proposeChapter(paragraphs = 2) - val chapter = itemEvents(chapterSession.id).first() - val scaffoldSession = proposeScaffolding( - chapter, - index = 0, - translationIds = listOf("1".repeat(64)) - ) - - val lines = db.chatMessageDao().getChatMessagesByChatRoomId(roomId) - .map { it.chatMessage } - .filter { it.messageType in ChatMessage.FROST_TYPES } - - // Both sessions announce themselves and both publish this device's nonce, - // so the transcript holds one session's lines interleaved with the other's - // -- and every line says which of the two it belongs to. - val bySession = lines.groupBy { it.frostSigningSessionId } - - assertEquals(setOf(chapterSession.id, scaffoldSession.id), bySession.keys) - assertTrue(bySession.values.all { it.isNotEmpty() }) - - // Which is what the transcript's rules are read through. Nothing else on - // these rows can tell them apart: the two sessions are running at the same - // time and write the same types, so before the sessions were on the rows a - // line of one was read as evidence about the other -- and the reader's - // second proposal lost its "Review" the moment the first was answered. - assertTrue( - ChatMessage.answeredRequests(lines).isEmpty(), - "a proposer is never asked to approve their own proposal" - ) - } - - @Test - fun `the two sessions never share nonce material`() = runBlocking { - openDevice() - - val chapterSession = proposeChapter(paragraphs = 2) - val chapter = itemEvents(chapterSession.id).first() - val scaffoldSession = proposeScaffolding( - chapter, - index = 0, - translationIds = listOf("1".repeat(64), "2".repeat(64)) - ) - - // The one thing concurrency could get wrong. Two partial signatures - // under a single secret nonce are two equations in one unknown, and the - // share falls out; seeds are minted per item per session precisely so - // that running two at once cannot arrange it. - val seeds = ( - db.frostSigningSessionDao().getItems(chapterSession.id) + - db.frostSigningSessionDao().getItems(scaffoldSession.id) - ).map { it.nonceRandom } - - assertEquals(5, seeds.size) - assertEquals(seeds.size, seeds.distinct().size) - } - - @Test - fun `the caps do not compete`() = runBlocking { - openDevice() - - // The reason the scaffolding is a second session rather than more items - // on the chapter's. A chapter of the longest allowed length still - // proposes with translations waiting for it; sharing one batch, every - // dialect the group worked in would have cost it a paragraph. - val translationIds = (1..8).map { it.toString().repeat(64).take(64) } - - val chapterSession = proposeChapter(paragraphs = AddChapterViewModel.MAX_CHUNKS_PER_CHAPTER) - val chapter = itemEvents(chapterSession.id).first() - val scaffoldSession = proposeScaffolding(chapter, index = 0, translationIds = translationIds) - - assertEquals(FrostSigningManager.MAX_BATCH_SIZE, itemEvents(chapterSession.id).size) - assertEquals(translationIds.size, itemEvents(scaffoldSession.id).size) - } - - @Test - fun `an artifact longer than one session is split across two`() = runBlocking { - openDevice() - - // What `addTranslation` does with an artifact past the cap: the - // translation and as many chapters as fit, then the rest naming the - // translation the first session is about to sign. Refusing instead - // would be a cap on how long a book may be, dressed up as a cap on a - // batch. - val chapters = sourceChapters(AddTranslationArtifactVersionViewModel.MAX_CHAPTERS_PER_TRANSLATION + 3) - - val first = proposeTranslation( - chapters.take(AddTranslationArtifactVersionViewModel.MAX_CHAPTERS_PER_TRANSLATION) - ) - val translation = itemEvents(first.id).first() - val second = FrostSigningManager.proposeSigningBatch( - database = db, - localChatRoom = room, - userPublicKey = proposer, - events = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translation.id), - chapters = chapters.drop(AddTranslationArtifactVersionViewModel.MAX_CHAPTERS_PER_TRANSLATION) - .map(TranslationScaffold.SourceChapter::of), - createdAt = translation.createdAt, - ) - ) - - assertEquals(FrostSigningManager.MAX_BATCH_SIZE, itemEvents(first.id).size) - assertEquals(3, itemEvents(second.id).size) - - // Every chapter of the work is covered exactly once, across both, and - // each names the translation as the group will author it. - val scaffolded = (itemEvents(first.id).drop(1) + itemEvents(second.id)).map { - TranslationChapterEvent(it.id, it.pubKey, it.createdAt, it.tags, it.content, it.sig) - } - assertEquals(chapters.map { it.id }, scaffolded.map { it.chapterId() }) - assertEquals(chapters.map { it.index }, scaffolded.map { it.index() }) - assertTrue(scaffolded.all { it.translationArtifactVersionId() == translation.id }) - } - - @Test - fun `one session is still refused a chapter too many`() = runBlocking { - openDevice() - - // Refused rather than truncated: a batch that quietly dropped its last - // chapters would sign a translation the group believes covers the whole - // work while the end of it can never be translated. The screen splits - // before it gets here, so this is never what a member sees -- but the - // screen is not what enforces it. - assertFailsWith { - proposeTranslation(sourceChapters(FrostSigningManager.MAX_BATCH_SIZE)) - } - - assertEquals(emptyList(), db.frostSigningSessionDao().getSessionsForChatRoom(roomId)) - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/StringCatalogueJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/StringCatalogueJvmTest.kt index 2e0c0980..b581c572 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/StringCatalogueJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/StringCatalogueJvmTest.kt @@ -5,8 +5,7 @@ import bennu.composeapp.generated.resources.Res import bennu.composeapp.generated.resources.currently_no_messages_have_been_shared import bennu.composeapp.generated.resources.don_t_sign import bennu.composeapp.generated.resources.something_went_wrong -import bennu.composeapp.generated.resources.add_chapter_to -import bennu.composeapp.generated.resources.chapter_words_characters +import bennu.composeapp.generated.resources.recovered_of_still_unreadable import bennu.composeapp.generated.resources.sent_a_private_message_to import org.jetbrains.compose.resources.getString import kotlin.test.Test @@ -56,8 +55,8 @@ class StringCatalogueJvmTest { // and reads plausibly -- "Recovered 3 of 12" against "Recovered 12 of 3" -- so // the ordering is worth asserting on a multi-argument one. assertEquals( - "Add chapter to Genesis", - getString(Res.string.add_chapter_to, "Genesis"), + "Recovered 3 of 12 · 9 still unreadable.", + getString(Res.string.recovered_of_still_unreadable, "3", "12", "9", "."), ) assertEquals( "Ada sent a private message to Grace", @@ -71,8 +70,8 @@ class StringCatalogueJvmTest { // decodes it and the resource holds the character. If it had been left alone the // app would render the six characters of the escape. assertEquals( - "Chapter 3 · 900 words · 4800 characters", - getString(Res.string.chapter_words_characters, "3", "900", "4800"), + "Recovered 3 of 12 · 9 still unreadable", + getString(Res.string.recovered_of_still_unreadable, "3", "12", "9", ""), ) } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomMemberRowJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomMemberRowJvmTest.kt index dc3ce8d2..a6b45afe 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomMemberRowJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomMemberRowJvmTest.kt @@ -12,7 +12,6 @@ import com.machankura.bennu.compose.database.model.Participant import com.machankura.bennu.compose.database.model.Profile import com.machankura.bennu.compose.database.model.intermdiate.LocalParticipant import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.MantraRepository import com.machankura.bennu.compose.repository.NostrRepository import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId @@ -112,7 +111,6 @@ class ChatRoomMemberRowJvmTest { initialChatRoomDetailUIState = state(), nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, onNavigateToRoute = onNavigateToRoute, onPopBackToRoute = {}, onNavigateBack = {}, diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt index d652b4f6..c1f443f6 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt @@ -17,7 +17,6 @@ import com.machankura.bennu.compose.nostr.GroupNostrProfile import com.machankura.bennu.compose.nostr.GroupPost import com.machankura.bennu.compose.nostr.GroupRelayList import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.MantraRepository import com.machankura.bennu.compose.repository.NostrRepository import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId @@ -239,7 +238,6 @@ class GroupSignedWorkRowsJvmTest { initialChatRoomDetailUIState = uiState, nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, onNavigateToRoute = onNavigateToRoute, onPopBackToRoute = {}, onNavigateBack = {},