From 8ee70ce991ff5d922128dd6cf52cb90111dab217 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sat, 22 Aug 2026 15:48:33 +0200 Subject: [PATCH 1/3] refactor: drop swipe to dismiss --- .../dashboard/presentation/DashboardGraph.kt | 4 +- .../keygo/core/item/data/local/dao/ItemDao.kt | 8 +- .../data/repository/ItemRepositoryImpl.kt | 17 +- .../item/domain/repository/ItemRepository.kt | 6 +- .../item/data/local/dao/ItemDaoSearchTest.kt | 9 +- .../core/item/data/local/dao/TagDaoTest.kt | 4 +- .../data/repository/ItemRepositoryImplTest.kt | 42 +- .../keygo/core/item/FakeItemRepository.kt | 37 +- .../core/ui/components/DeletableVaultItem.kt | 364 ------------------ .../ui/components/HapticSwipeToDismissBox.kt | 39 -- .../core/ui/components/KeyGoLazyColumn.kt | 94 ++--- .../main/res/drawable/avd_delete_forever.xml | 62 --- .../de/davis/keygo/core/util/Combine.kt | 24 ++ .../util/data/snackbar/SnackbarManagerImpl.kt | 16 +- .../domain/model/snackbar/SnackbarAction.kt | 8 - .../domain/model/snackbar/SnackbarMessage.kt | 3 - .../util/domain/snackbar/SnackbarManager.kt | 4 - .../snackbar/ObserveSnackbarEvents.kt | 42 +- .../data/snackbar/SnackbarManagerImplTest.kt | 65 +--- .../presentation/ItemListScreen.kt | 14 +- .../presentation/ItemListViewModel.kt | 100 ++--- .../presentation/SnackbarMessages.kt | 19 - .../components/DeleteItemsDialog.kt | 61 +++ .../components/ItemListContent.kt | 44 ++- .../components/SelectionTopBar.kt | 65 ++++ .../list_screen/presentation/model/Event.kt | 2 +- .../presentation/model/ListItemState.kt | 5 +- .../src/main/res/values/strings.xml | 17 +- .../presentation/ItemListViewModelTest.kt | 274 +++++++++++++ 29 files changed, 686 insertions(+), 763 deletions(-) delete mode 100644 core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/DeletableVaultItem.kt delete mode 100644 core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/HapticSwipeToDismissBox.kt delete mode 100644 core/ui/src/main/res/drawable/avd_delete_forever.xml delete mode 100644 core/util/src/main/kotlin/de/davis/keygo/core/util/domain/model/snackbar/SnackbarAction.kt delete mode 100644 feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/SnackbarMessages.kt create mode 100644 feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/DeleteItemsDialog.kt create mode 100644 feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/SelectionTopBar.kt create mode 100644 feature/list_screen/src/test/kotlin/de/davis/keygo/feature/list_screen/presentation/ItemListViewModelTest.kt diff --git a/app/src/main/kotlin/de/davis/keygo/dashboard/presentation/DashboardGraph.kt b/app/src/main/kotlin/de/davis/keygo/dashboard/presentation/DashboardGraph.kt index 0ade56072..a6b867980 100644 --- a/app/src/main/kotlin/de/davis/keygo/dashboard/presentation/DashboardGraph.kt +++ b/app/src/main/kotlin/de/davis/keygo/dashboard/presentation/DashboardGraph.kt @@ -85,8 +85,8 @@ fun NavGraphBuilder.dashboardGraph( ) } }, - onItemDelete = { deleted, firstItemId -> - if (openedItemId == deleted) { + onItemsDelete = { deleted, firstItemId -> + if (openedItemId in deleted) { scope.launch { if (!isSinglePaneMode && !isModifyScreenActive) firstItemId?.let { diff --git a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/dao/ItemDao.kt b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/dao/ItemDao.kt index f3efadeec..3514a0ce8 100644 --- a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/dao/ItemDao.kt +++ b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/dao/ItemDao.kt @@ -20,8 +20,8 @@ internal interface ItemDao { @Upsert suspend fun upsert(item: ItemEntity): Long - @Query("DELETE FROM item WHERE id = :id") - suspend fun delete(id: ItemId) + @Query("DELETE FROM item WHERE id IN (:ids)") + suspend fun delete(ids: Collection) @Query("SELECT name FROM item WHERE id = :id") suspend fun getNameById(id: ItemId): String? @@ -60,11 +60,11 @@ internal interface ItemDao { OR tm.item_id IS NOT NULL) """ ) - suspend fun searchItem( + fun searchItem( query: String, normalizedQuery: String, itemType: VaultItemType? = null, - ): List + ): Flow> @Query("UPDATE item SET pinned = :pinned WHERE id = :id") suspend fun setPinned(id: ItemId, pinned: Boolean) diff --git a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/repository/ItemRepositoryImpl.kt b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/repository/ItemRepositoryImpl.kt index f02b3154f..d4fd0c11a 100644 --- a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/repository/ItemRepositoryImpl.kt +++ b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/repository/ItemRepositoryImpl.kt @@ -33,9 +33,13 @@ internal class ItemRepositoryImpl( private val tagDao: TagDao, ) : ItemRepository { - override suspend fun deleteItem(itemId: ItemId): Unit = database.withTransaction { - val tagIds = tagDao.tagIdsForItem(itemId) - itemDao.delete(itemId) + override suspend fun deleteItems(itemIds: Set): Unit = database.withTransaction { + if (itemIds.isEmpty()) return@withTransaction + + // Collected before the delete: once the rows are gone the cross refs are too, so the + // orphan sweep would have nothing left to look at. + val tagIds = itemIds.flatMap { tagDao.tagIdsForItem(it) }.distinct() + itemDao.delete(itemIds) if (tagIds.isNotEmpty()) tagDao.pruneOrphans(tagIds) } @@ -55,11 +59,12 @@ internal class ItemRepositoryImpl( vaultId: VaultId?, ): Boolean = itemDao.existsName(name, excludeId, vaultId) - override suspend fun searchVaultItem( + override fun searchVaultItem( query: String, itemType: VaultItemType?, - ): List = itemDao.searchItem(query, Tag.normalize(query), itemType) - .map(LightweightItemSearchResult::toDomain) + ): Flow> = + itemDao.searchItem(query, Tag.normalize(query), itemType) + .map { results -> results.map(LightweightItemSearchResult::toDomain) } override suspend fun setPinned(itemId: ItemId, pinned: Boolean) = itemDao.setPinned(itemId, pinned) diff --git a/core/item/src/main/kotlin/de/davis/keygo/core/item/domain/repository/ItemRepository.kt b/core/item/src/main/kotlin/de/davis/keygo/core/item/domain/repository/ItemRepository.kt index 5c0bd942f..a6d4fc2cc 100644 --- a/core/item/src/main/kotlin/de/davis/keygo/core/item/domain/repository/ItemRepository.kt +++ b/core/item/src/main/kotlin/de/davis/keygo/core/item/domain/repository/ItemRepository.kt @@ -14,7 +14,7 @@ import kotlinx.coroutines.flow.Flow interface ItemRepository { - suspend fun deleteItem(itemId: ItemId) + suspend fun deleteItems(itemIds: Set) suspend fun createOrUpdateVaultItem(item: Item): ItemId @@ -26,10 +26,10 @@ interface ItemRepository { vaultId: VaultId? = null ): Boolean - suspend fun searchVaultItem( + fun searchVaultItem( query: String, itemType: VaultItemType? = null - ): List + ): Flow> suspend fun setPinned(itemId: ItemId, pinned: Boolean) diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/local/dao/ItemDaoSearchTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/local/dao/ItemDaoSearchTest.kt index 3522574bf..867257d5e 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/local/dao/ItemDaoSearchTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/local/dao/ItemDaoSearchTest.kt @@ -15,6 +15,7 @@ import de.davis.keygo.core.item.domain.model.Vault import de.davis.keygo.core.item.generated.domain.model.VaultItemType import io.mockk.mockk import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest import kotlin.test.AfterTest @@ -83,7 +84,7 @@ internal class ItemDaoSearchTest { fun `searchItem matches an item by tag value only`() = runTest { val id = insertItem(name = "Chase", note = null, tags = setOf("Banking")) - val results = itemDao.searchItem(query = "Bank", normalizedQuery = "bank") + val results = itemDao.searchItem(query = "Bank", normalizedQuery = "bank").first() assertEquals(1, results.size) val r = results.single() @@ -97,7 +98,7 @@ internal class ItemDaoSearchTest { fun `searchItem still matches by name and sets matchedName`() = runTest { insertItem(name = "Bank of Earth") - val r = itemDao.searchItem(query = "Bank", normalizedQuery = "bank").single() + val r = itemDao.searchItem(query = "Bank", normalizedQuery = "bank").first().single() assertTrue(r.matchedName) assertFalse(r.matchedTag) @@ -107,7 +108,7 @@ internal class ItemDaoSearchTest { fun `searchItem does not return items with no name note or tag match`() = runTest { insertItem(name = "Email", note = "personal", tags = setOf("Mail")) - assertTrue(itemDao.searchItem(query = "Bank", normalizedQuery = "bank").isEmpty()) + assertTrue(itemDao.searchItem(query = "Bank", normalizedQuery = "bank").first().isEmpty()) } @Test @@ -120,7 +121,7 @@ internal class ItemDaoSearchTest { query = "Bank", normalizedQuery = "bank", itemType = VaultItemType.Login, - ).size, + ).first().size, ) } } diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/local/dao/TagDaoTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/local/dao/TagDaoTest.kt index 662fa8ada..67c1c0e23 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/local/dao/TagDaoTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/local/dao/TagDaoTest.kt @@ -104,7 +104,7 @@ internal class TagDaoTest { val item = insertItem() tagDao.syncTags(item, setOf(tag("Work"))) - db.itemDao().delete(item) + db.itemDao().delete(setOf(item)) assertEquals(emptyList(), tagDao.tagIdsForItem(item)) } @@ -128,7 +128,7 @@ internal class TagDaoTest { tagDao.syncTags(item, setOf(tag("Temp"))) val tagIds = tagDao.tagIdsForItem(item) - db.itemDao().delete(item) + db.itemDao().delete(setOf(item)) tagDao.pruneOrphans(tagIds) assertNull(tagDao.findIdByNormalized("temp")) diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/ItemRepositoryImplTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/ItemRepositoryImplTest.kt index a15c2b29a..571a4930d 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/ItemRepositoryImplTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/ItemRepositoryImplTest.kt @@ -5,6 +5,7 @@ import de.davis.keygo.core.item.data.local.dao.ItemDao import de.davis.keygo.core.item.data.local.dao.TagDao import de.davis.keygo.core.item.data.local.datasource.ItemDatabase import de.davis.keygo.core.item.data.local.pojo.ItemTagProjection +import de.davis.keygo.core.item.domain.alias.ItemId import de.davis.keygo.core.item.domain.alias.newItemId import de.davis.keygo.core.item.domain.model.Tag import io.mockk.coEvery @@ -46,29 +47,60 @@ class ItemRepositoryImplTest { fun tearDown() = unmockkStatic("androidx.room.RoomDatabaseKt") @Test - fun `deleteItem captures tag ids, deletes item, then prunes those tags`() = runTest { + fun `deleteItems captures tag ids, deletes items, then prunes those tags`() = runTest { val id = newItemId() coEvery { tagDao.tagIdsForItem(id) } returns listOf(7L, 9L) - repository.deleteItem(id) + repository.deleteItems(setOf(id)) coVerifyOrder { tagDao.tagIdsForItem(id) - itemDao.delete(id) + itemDao.delete(setOf(id)) tagDao.pruneOrphans(listOf(7L, 9L)) } } @Test - fun `deleteItem skips prune when item had no tags`() = runTest { + fun `deleteItems skips prune when items had no tags`() = runTest { val id = newItemId() coEvery { tagDao.tagIdsForItem(id) } returns emptyList() - repository.deleteItem(id) + repository.deleteItems(setOf(id)) coVerify(exactly = 0) { tagDao.pruneOrphans(any()) } } + @Test + fun `deleteItems removes every id in one dao call`() = runTest { + val first = newItemId() + val second = newItemId() + coEvery { tagDao.tagIdsForItem(any()) } returns emptyList() + + repository.deleteItems(setOf(first, second)) + + coVerify(exactly = 1) { itemDao.delete(setOf(first, second)) } + } + + @Test + fun `deleteItems prunes each tag once when items share a tag`() = runTest { + val first = newItemId() + val second = newItemId() + coEvery { tagDao.tagIdsForItem(first) } returns listOf(7L) + coEvery { tagDao.tagIdsForItem(second) } returns listOf(7L, 9L) + + repository.deleteItems(setOf(first, second)) + + coVerify { tagDao.pruneOrphans(listOf(7L, 9L)) } + } + + @Test + fun `deleteItems touches nothing when the set is empty`() = runTest { + repository.deleteItems(emptySet()) + + coVerify(exactly = 0) { itemDao.delete(any>()) } + coVerify(exactly = 0) { tagDao.pruneOrphans(any()) } + } + @Test fun `observeTagsByItem groups rows into a tag set per item`() = runTest { val a = newItemId() diff --git a/core/item/src/testFixtures/kotlin/de/davis/keygo/core/item/FakeItemRepository.kt b/core/item/src/testFixtures/kotlin/de/davis/keygo/core/item/FakeItemRepository.kt index fb77c8856..cb5f639e4 100644 --- a/core/item/src/testFixtures/kotlin/de/davis/keygo/core/item/FakeItemRepository.kt +++ b/core/item/src/testFixtures/kotlin/de/davis/keygo/core/item/FakeItemRepository.kt @@ -13,8 +13,8 @@ import de.davis.keygo.core.item.domain.repository.ItemRepository import de.davis.keygo.core.item.generated.domain.model.VaultItemType import de.davis.keygo.core.util.Result import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.update /** * In-memory [ItemRepository] for tests. @@ -68,7 +68,13 @@ class FakeItemRepository( .associate { item -> item.id to item.tags.toSet() } } - override suspend fun deleteItem(itemId: ItemId) = Unit + override suspend fun deleteItems(itemIds: Set) { + allStores.update { store -> store - itemIds } + itemIds.forEach { id -> + envelopes.remove(id) + itemTypes.remove(id) + } + } override suspend fun createOrUpdateVaultItem(item: Item): ItemId = item.id @@ -88,15 +94,36 @@ class FakeItemRepository( (vaultId == null || it.vaultId == vaultId) } - override suspend fun searchVaultItem( + override fun searchVaultItem( query: String, itemType: VaultItemType?, - ): List = emptyList() + ): Flow> = allStores.map { store -> + store.values + .filter { itemType == null || it.itemType == itemType } + .mapNotNull { item -> + val matchedName = item.name.contains(query, ignoreCase = true) + val matchedNote = item.note?.contains(query, ignoreCase = true) == true + val matchedTag = item.tags.any { it.display.contains(query, ignoreCase = true) } + if (!matchedName && !matchedNote && !matchedTag) return@mapNotNull null + + LiteItemSearchResult( + id = item.id, + name = item.name, + itemType = item.itemType, + pinned = item.pinned, + matchedName = matchedName, + matchedNote = matchedNote, + matchedTag = matchedTag, + ) + } + } override suspend fun setPinned(itemId: ItemId, pinned: Boolean) = Unit override fun observeLiteVaultItems(vaultId: VaultId?): Flow> = - flowOf(emptyList()) + allStores.map { store -> + store.values.filter { vaultId == null || it.vaultId == vaultId } + } override suspend fun getItemKeyEnvelope(itemId: ItemId): ItemKeyEnvelope? = envelopes[itemId] diff --git a/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/DeletableVaultItem.kt b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/DeletableVaultItem.kt deleted file mode 100644 index 4a467355d..000000000 --- a/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/DeletableVaultItem.kt +++ /dev/null @@ -1,364 +0,0 @@ -@file:OptIn(ExperimentalMaterial3ExpressiveApi::class) - -package de.davis.keygo.core.ui.components - -import android.content.res.Configuration -import androidx.compose.animation.core.animateFloatAsState -import androidx.compose.animation.graphics.res.animatedVectorResource -import androidx.compose.animation.graphics.res.rememberAnimatedVectorPainter -import androidx.compose.animation.graphics.vector.AnimatedImageVector -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.shape.CornerBasedShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.ListItemDefaults -import androidx.compose.material3.ListItemShapes -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.SegmentedListItem -import androidx.compose.material3.Surface -import androidx.compose.material3.SwipeToDismissBoxState -import androidx.compose.material3.SwipeToDismissBoxValue -import androidx.compose.material3.Text -import androidx.compose.material3.rememberSwipeToDismissBoxState -import androidx.compose.runtime.Composable -import androidx.compose.runtime.DisposableEffect -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.Stable -import androidx.compose.runtime.derivedStateOf -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableFloatStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshotFlow -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.drawBehind -import androidx.compose.ui.geometry.CornerRadius -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.geometry.Size -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.ColorFilter -import androidx.compose.ui.graphics.drawscope.translate -import androidx.compose.ui.layout.onSizeChanged -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.tooling.preview.Preview -import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.dp -import de.davis.keygo.core.ui.R -import de.davis.keygo.core.ui.theme.KeyGoTheme -import kotlinx.coroutines.launch -import kotlin.math.absoluteValue - -private fun CornerBasedShape.lerpShape(other: CornerBasedShape, fraction: Float): CornerBasedShape = - lerp(other as Any, fraction) as CornerBasedShape - -private val CircleRoundedShape = RoundedCornerShape(50) - -@Stable -class SegmentedShapeCoordinator( - private val overrideShape: RoundedCornerShape, - private val defaultShapes: ListItemShapes, - private val defaultBaseShape: CornerBasedShape, -) { - var swipingIndex by mutableStateOf(null) - internal set - var swipingProgress by mutableFloatStateOf(0f) - internal set - - fun onSwipeProgressChange(index: Int, progress: Float) { - if (progress > 0f) { - swipingIndex = index - swipingProgress = progress - } else if (swipingIndex == index) { - swipingIndex = null - swipingProgress = 0f - } - } - - internal fun computeShapes( - isFirstFraction: Float, - isLastFraction: Float, - isSwiping: Boolean, - morphIsFirstProgress: Float, - morphIsLastProgress: Float, - ): ListItemShapes { - // Position-animated base: lerp top/bottom corners independently - val topTarget = defaultBaseShape.copy( - topStart = overrideShape.topStart, - topEnd = overrideShape.topEnd, - ) - val topLerped = defaultBaseShape.lerpShape(topTarget, isFirstFraction) - - val bottomTarget = defaultBaseShape.copy( - bottomStart = overrideShape.bottomStart, - bottomEnd = overrideShape.bottomEnd, - ) - val bottomLerped = defaultBaseShape.lerpShape(bottomTarget, isLastFraction) - - val baseShape = topLerped.copy( - bottomStart = bottomLerped.bottomStart, - bottomEnd = bottomLerped.bottomEnd, - ) - - if (morphIsFirstProgress == 0f && morphIsLastProgress == 0f) - return defaultShapes.copy(shape = baseShape) - - // Swipe morphing on top of the position-animated base - val morphTarget = if (isSwiping) CircleRoundedShape else overrideShape - - val swipeTopTarget = baseShape.copy( - topStart = morphTarget.topStart, - topEnd = morphTarget.topEnd, - ) - val swipeTopLerped = baseShape.lerpShape(swipeTopTarget, morphIsFirstProgress) - - val swipeBottomTarget = baseShape.copy( - bottomStart = morphTarget.bottomStart, - bottomEnd = morphTarget.bottomEnd, - ) - val swipeBottomLerped = baseShape.lerpShape(swipeBottomTarget, morphIsLastProgress) - - return defaultShapes.copy( - shape = swipeTopLerped.copy( - bottomStart = swipeBottomLerped.bottomStart, - bottomEnd = swipeBottomLerped.bottomEnd, - ) - ) - } -} - -@Composable -fun rememberSegmentedShapeCoordinator( - defaultShapes: ListItemShapes = ListItemDefaults.shapes(), -): SegmentedShapeCoordinator { - val overrideShape = MaterialTheme.shapes.large as RoundedCornerShape - val defaultBaseShape = defaultShapes.shape - return remember(overrideShape, defaultShapes) { - SegmentedShapeCoordinator( - overrideShape = overrideShape, - defaultShapes = defaultShapes, - defaultBaseShape = defaultBaseShape as CornerBasedShape, - ) - } -} - -@Composable -fun rememberSegmentedShapes( - coordinator: SegmentedShapeCoordinator, - index: Int, - isFirst: Boolean, - isLast: Boolean, -): ListItemShapes { - val isFirstFraction by animateFloatAsState(if (isFirst) 1f else 0f) - val isLastFraction by animateFloatAsState(if (isLast) 1f else 0f) - - val swiping = coordinator.swipingIndex - val progress = if (swiping == null) 0f else coordinator.swipingProgress - - val targetFirst = when (swiping) { - index -> progress - index - 1 if !isFirst -> progress - else -> 0f - } - val targetLast = when (swiping) { - index -> progress - index + 1 if !isLast -> progress - else -> 0f - } - - val morphFirst by animateFloatAsState(targetFirst) - val morphLast by animateFloatAsState(targetLast) - val isSwiping = swiping == index - - return remember(isFirstFraction, isLastFraction, isSwiping, morphFirst, morphLast) { - coordinator.computeShapes(isFirstFraction, isLastFraction, isSwiping, morphFirst, morphLast) - } -} - -@Composable -fun DeletableVaultItem( - title: String, - description: String, - onClick: () -> Unit, - onLongClick: () -> Unit, - onDeleteRequested: suspend () -> Boolean, - shapeCoordinator: SegmentedShapeCoordinator, - itemIndex: Int, - isFirst: Boolean, - isLast: Boolean, - modifier: Modifier = Modifier, - selected: Boolean = false, - containerColor: Color = MaterialTheme.colorScheme.surfaceContainerHigh, - selectedContainerColor: Color = MaterialTheme.colorScheme.secondaryContainer, - enableSwipeToDelete: Boolean = true, - shapeMorphThreshold: Dp = 48.dp, - leadingContent: @Composable (() -> Unit)? = null, -) { - val shapes = rememberSegmentedShapes(shapeCoordinator, itemIndex, isFirst, isLast) - val state = rememberSwipeToDismissBoxState() - - val currentOnDeleteRequested by rememberUpdatedState(onDeleteRequested) - val scope = rememberCoroutineScope() - - val morphThresholdPx = with(LocalDensity.current) { shapeMorphThreshold.toPx() } - LaunchedEffect(state, morphThresholdPx) { - snapshotFlow { - (state.offsetOrZero().absoluteValue / morphThresholdPx).coerceIn(0f, 1f) - }.collect { shapeCoordinator.onSwipeProgressChange(itemIndex, it) } - } - DisposableEffect(Unit) { - onDispose { shapeCoordinator.onSwipeProgressChange(itemIndex, 0f) } - } - - HapticSwipeToDismissBox( - backgroundContent = { - DeletableVaultItemBackground(state = state) - }, - modifier = modifier, - allowSwipe = enableSwipeToDelete, - state = state, - onDismiss = { - scope.launch { - val shouldDelete = currentOnDeleteRequested() - if (!shouldDelete) { - state.snapTo(SwipeToDismissBoxValue.Settled) - } - } - } - ) { - SegmentedListItem( - selected = selected, - onClick = onClick, - onLongClick = onLongClick, - shapes = shapes, - colors = ListItemDefaults.segmentedColors( - containerColor = containerColor, - selectedContainerColor = selectedContainerColor, - ), - leadingContent = leadingContent, - supportingContent = { - Text(text = description) - } - ) { - Text(text = title) - } - } -} - -@Composable -fun DeletableVaultItemBackground(state: SwipeToDismissBoxState) { - val containerColor = MaterialTheme.colorScheme.error - val contentColor = MaterialTheme.colorScheme.onError - val gap = 4.dp - val iconSize = 28.dp - - var itemHeightPx by remember { mutableFloatStateOf(0f) } - val gapPx = with(LocalDensity.current) { gap.toPx() } - - val isIconFullyVisible by remember { - derivedStateOf { - if (itemHeightPx == 0f) false else { - val offset = state.offsetOrZero() - val drawWidth = offset.absoluteValue - gapPx - - // Alpha hits 1f exactly when the drawWidth equals the item height (forming a perfect circle) - drawWidth >= itemHeightPx - } - } - } - - val animatedTrashCan = AnimatedImageVector.animatedVectorResource(R.drawable.avd_delete_forever) - val painter = rememberAnimatedVectorPainter( - animatedImageVector = animatedTrashCan, - atEnd = isIconFullyVisible - ) - - Box( - modifier = Modifier - .fillMaxSize() - .onSizeChanged { itemHeightPx = it.height.toFloat() } - .drawBehind { - val offset = state.offsetOrZero() - - val swipedWidth = offset.absoluteValue - val drawWidth = swipedWidth - gapPx - if (drawWidth < 1f) return@drawBehind - - val left = if (offset > 0f) 0f else size.width - drawWidth - - drawRoundRect( - color = containerColor, - topLeft = Offset(left, 0f), - size = Size(drawWidth, size.height), - cornerRadius = CornerRadius(size.height / 2f), - ) - - val iconSizePx = iconSize.toPx() - - val targetX = left + (drawWidth / 2f) - (iconSizePx / 2f) - val targetY = (size.height / 2f) - (iconSizePx / 2f) - - // linear normalization - val iconAlpha = drawWidth.mapToFraction(iconSizePx + gapPx, size.height) - - translate(left = targetX, top = targetY) { - with(painter) { - draw( - size = Size(iconSizePx, iconSizePx), - alpha = iconAlpha, - colorFilter = ColorFilter.tint(contentColor) - ) - } - } - }, - ) -} - -/** - * Maps a continuous Float value to a 0f..1f fraction based on a given range. - * The result is safely clamped between 0f and 1f. - * - * @receiver The value to be mapped. - * @param min The minimum value of the range. - * @param max The maximum value of the range. - * - * @return The corresponding fraction between 0f and 1f. - */ -private fun Float.mapToFraction(min: Float, max: Float): Float { - val range = (max - min).coerceAtLeast(1f) // Prevent division by zero - return ((this - min) / range).coerceIn(0f, 1f) -} - -private fun SwipeToDismissBoxState.offsetOrZero(): Float = runCatching { - requireOffset() -}.getOrDefault(0f) - -@Preview -@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL) -@Composable -private fun VaultItemPreview() { - val shapeCoordinator = rememberSegmentedShapeCoordinator() - KeyGoTheme { - Surface(modifier = Modifier.fillMaxSize()) { - Column { - DeletableVaultItem( - title = "My Element", - description = "Password", - onClick = {}, - onLongClick = {}, - onDeleteRequested = { - false - }, - shapeCoordinator = shapeCoordinator, - itemIndex = 3, - isFirst = false, - isLast = true, - ) - } - } - } -} \ No newline at end of file diff --git a/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/HapticSwipeToDismissBox.kt b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/HapticSwipeToDismissBox.kt deleted file mode 100644 index 4a7ca6056..000000000 --- a/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/HapticSwipeToDismissBox.kt +++ /dev/null @@ -1,39 +0,0 @@ -package de.davis.keygo.core.ui.components - -import androidx.compose.foundation.layout.RowScope -import androidx.compose.material3.SwipeToDismissBox -import androidx.compose.material3.SwipeToDismissBoxState -import androidx.compose.material3.SwipeToDismissBoxValue -import androidx.compose.material3.rememberSwipeToDismissBoxState -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Modifier -import androidx.compose.ui.hapticfeedback.HapticFeedbackType -import androidx.compose.ui.platform.LocalHapticFeedback - -@Composable -internal fun HapticSwipeToDismissBox( - backgroundContent: @Composable RowScope.() -> Unit, - modifier: Modifier = Modifier, - allowSwipe: Boolean = true, - state: SwipeToDismissBoxState = rememberSwipeToDismissBoxState(), - onDismiss: (SwipeToDismissBoxValue) -> Unit = {}, - content: @Composable RowScope.() -> Unit, -) { - val hapticFeedback = LocalHapticFeedback.current - LaunchedEffect(state.targetValue) { - if (state.targetValue != SwipeToDismissBoxValue.Settled) { - hapticFeedback.performHapticFeedback(HapticFeedbackType.GestureThresholdActivate) - } - } - - SwipeToDismissBox( - modifier = modifier, - state = state, - enableDismissFromStartToEnd = false, - enableDismissFromEndToStart = allowSwipe, - backgroundContent = backgroundContent, - onDismiss = onDismiss, - content = content - ) -} \ No newline at end of file diff --git a/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/KeyGoLazyColumn.kt b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/KeyGoLazyColumn.kt index cde7aa43d..422c183c0 100644 --- a/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/KeyGoLazyColumn.kt +++ b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/KeyGoLazyColumn.kt @@ -17,7 +17,9 @@ import androidx.compose.material.icons.filled.PushPin import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon import androidx.compose.material3.ListItemDefaults +import androidx.compose.material3.ListItemShapes import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SegmentedListItem import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.contentColorFor @@ -32,7 +34,6 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.platform.LocalDensity @@ -59,28 +60,13 @@ data class KeyGoColumnItem( @Composable fun KeyGoColumn( items: List>, - onDelete: (ID) -> Unit, onItemClick: (ID) -> Unit, onItemLongClick: (ID) -> Unit, modifier: Modifier = Modifier, - enableSwipeToDelete: Boolean = true, openedItemId: ID? = null, selectedItemIds: Set = emptySet(), ) { - val (firstInGroupIndices, lastInGroupIndices) = remember(items) { - val first = mutableSetOf() - val last = mutableSetOf() - - for (i in items.indices) { - if (i == 0 || items[i].header != items[i - 1].header) first.add(i) - if (i == items.lastIndex || items[i].header != items[i + 1].header) last.add(i) - } - - first to last - } - val listState = rememberLazyListState() - val shapeCoordinator = rememberSegmentedShapeCoordinator() @Composable fun containerColorForId(id: ID): Color = @@ -99,47 +85,31 @@ fun KeyGoColumn( ) { index, item -> val id = item.id - val isFirst = index in firstInGroupIndices - val isLast = index in lastInGroupIndices + val isFirst = items.isFirstInGroup(index) + val isLast = items.isLastInGroup(index) val bottomPadding = if (isLast && index != items.lastIndex) GroupVerticalPadding else 0.dp val containerColor by animateColorAsState(containerColorForId(id)) - DeletableVaultItem( - title = item.title, - description = item.itemType.presentation.first, + SegmentedListItem( onClick = { onItemClick(id) }, onLongClick = { onItemLongClick(id) }, - onDeleteRequested = { - onDelete(id) - // We return false here because it allows the swipe state to reset. - // When an item is successfully deleted, a new list containing the - // remaining items will be provided, causing the list to recompose - // with the updated data. The swipe state doesn't need to persist beyond - // the delete action, so resetting it is appropriate. - // If an error occurs during deletion and the item isn't removed, the - // swipe state will reset automatically since no new list is provided - // and no recomposition occurs. This ensures the UI remains consistent. - false - }, - shapeCoordinator = shapeCoordinator, - itemIndex = index, - isFirst = isFirst, - isLast = isLast, + shapes = segmentedShapesFor(isFirst = isFirst, isLast = isLast), + colors = ListItemDefaults.segmentedColors( + containerColor = containerColor, + selectedContainerColor = MaterialTheme.colorScheme.secondaryContainer, + ), modifier = Modifier .padding(bottom = bottomPadding) .expressiveAnimateItem(), - selected = id in selectedItemIds, - containerColor = containerColor, - enableSwipeToDelete = enableSwipeToDelete, leadingContent = { val isFirstVisibleItem by remember(index) { derivedStateOf { listState.firstVisibleItemIndex == index } } - if (index in firstInGroupIndices && !isFirstVisibleItem) { + if (isFirst && !isFirstVisibleItem) { KeyGoInlineHeader( header = item.header, color = contentColorFor(containerColorForId(id)) @@ -147,8 +117,14 @@ fun KeyGoColumn( } else { Spacer(modifier = Modifier.headerSize()) } - } - ) + }, + supportingContent = { + Text(text = item.itemType.presentation.first) + }, + selected = id in selectedItemIds, + ) { + Text(text = item.title) + } } } @@ -164,13 +140,14 @@ fun KeyGoColumn( } val density = LocalDensity.current - val headerOffset by remember(listState, lastInGroupIndices, density) { + val headerOffset by remember(listState, items, density) { derivedStateOf { val offset = with(density) { IntOffset(16.dp.roundToPx(), (10.dp + 6.dp).roundToPx()) } - if (listState.firstVisibleItemIndex in lastInGroupIndices) + val index = listState.firstVisibleItemIndex + if (index in items.indices && items.isLastInGroup(index)) offset.copy(y = offset.y - listState.firstVisibleItemScrollOffset) else offset } @@ -192,15 +169,6 @@ fun KeyGoColumn( } } - val headerAlpha by remember(shapeCoordinator, listState) { - derivedStateOf { - val swiping = shapeCoordinator.swipingIndex ?: return@derivedStateOf 1f - if (swiping == listState.firstVisibleItemIndex) - 1f - shapeCoordinator.swipingProgress * 2f - else 1f - } - } - val color by animateColorAsState( contentColorFor(containerColorForId(idBehindHeader)) ) @@ -210,9 +178,6 @@ fun KeyGoColumn( color = color, modifier = Modifier .offset { headerOffset } - .graphicsLayer { - alpha = headerAlpha - } .onGloballyPositioned { headerPositionY = it.positionInParent().y + it.size.height / 2f + with(density) { @@ -223,6 +188,20 @@ fun KeyGoColumn( } } +private fun List>.isFirstInGroup(index: Int) = + index == 0 || this[index].header != this[index - 1].header + +private fun List>.isLastInGroup(index: Int) = + index == lastIndex || this[index].header != this[index + 1].header + +@Composable +private fun segmentedShapesFor(isFirst: Boolean, isLast: Boolean): ListItemShapes = when { + isFirst && isLast -> ListItemDefaults.shapes(MaterialTheme.shapes.large) + isFirst -> ListItemDefaults.segmentedShapes(index = 0, count = 3) + isLast -> ListItemDefaults.segmentedShapes(index = 2, count = 3) + else -> ListItemDefaults.segmentedShapes(index = 1, count = 3) +} + @Composable context(scope: LazyItemScope) private fun Modifier.expressiveAnimateItem(): Modifier = with(scope) { @@ -290,7 +269,6 @@ private fun KeyGoLazyColumnPreview() { Surface { KeyGoColumn( items = items, - onDelete = {}, onItemClick = {}, onItemLongClick = {}, ) diff --git a/core/ui/src/main/res/drawable/avd_delete_forever.xml b/core/ui/src/main/res/drawable/avd_delete_forever.xml deleted file mode 100644 index 371abfbd4..000000000 --- a/core/ui/src/main/res/drawable/avd_delete_forever.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/core/util/src/main/kotlin/de/davis/keygo/core/util/Combine.kt b/core/util/src/main/kotlin/de/davis/keygo/core/util/Combine.kt index 77bf76151..316cd7daf 100644 --- a/core/util/src/main/kotlin/de/davis/keygo/core/util/Combine.kt +++ b/core/util/src/main/kotlin/de/davis/keygo/core/util/Combine.kt @@ -44,3 +44,27 @@ fun combine( values[6] as T7, ) } + +fun combine( + flow1: Flow, + flow2: Flow, + flow3: Flow, + flow4: Flow, + flow5: Flow, + flow6: Flow, + flow7: Flow, + flow8: Flow, + transform: (T1, T2, T3, T4, T5, T6, T7, T8) -> R, +): Flow = combineArray(flow1, flow2, flow3, flow4, flow5, flow6, flow7, flow8) { values -> + @Suppress("UNCHECKED_CAST") + transform( + values[0] as T1, + values[1] as T2, + values[2] as T3, + values[3] as T4, + values[4] as T5, + values[5] as T6, + values[6] as T7, + values[7] as T8, + ) +} diff --git a/core/util/src/main/kotlin/de/davis/keygo/core/util/data/snackbar/SnackbarManagerImpl.kt b/core/util/src/main/kotlin/de/davis/keygo/core/util/data/snackbar/SnackbarManagerImpl.kt index 53ce53e10..5da1db309 100644 --- a/core/util/src/main/kotlin/de/davis/keygo/core/util/data/snackbar/SnackbarManagerImpl.kt +++ b/core/util/src/main/kotlin/de/davis/keygo/core/util/data/snackbar/SnackbarManagerImpl.kt @@ -3,9 +3,6 @@ package de.davis.keygo.core.util.data.snackbar import de.davis.keygo.core.util.domain.model.snackbar.SnackbarMessage import de.davis.keygo.core.util.domain.snackbar.SnackbarManager import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.receiveAsFlow import org.koin.core.annotation.Single @@ -13,21 +10,10 @@ import org.koin.core.annotation.Single internal class SnackbarManagerImpl : SnackbarManager { private val oneShotChannel = Channel(Channel.BUFFERED) - private val _stickyMessage = MutableStateFlow(null) override val oneShotEvents = oneShotChannel.receiveAsFlow() - override val stickyMessage: StateFlow = _stickyMessage.asStateFlow() - override fun sendMessage(message: SnackbarMessage) { - if (message.action != null) { - _stickyMessage.value = message - } else { - oneShotChannel.trySend(message) - } - } - - override fun reset() { - _stickyMessage.value = null + oneShotChannel.trySend(message) } } diff --git a/core/util/src/main/kotlin/de/davis/keygo/core/util/domain/model/snackbar/SnackbarAction.kt b/core/util/src/main/kotlin/de/davis/keygo/core/util/domain/model/snackbar/SnackbarAction.kt deleted file mode 100644 index f4a43c7a2..000000000 --- a/core/util/src/main/kotlin/de/davis/keygo/core/util/domain/model/snackbar/SnackbarAction.kt +++ /dev/null @@ -1,8 +0,0 @@ -package de.davis.keygo.core.util.domain.model.snackbar - -import de.davis.keygo.core.util.presentation.UIText - -data class SnackbarAction( - val label: UIText, - val onClick: () -> Unit, -) \ No newline at end of file diff --git a/core/util/src/main/kotlin/de/davis/keygo/core/util/domain/model/snackbar/SnackbarMessage.kt b/core/util/src/main/kotlin/de/davis/keygo/core/util/domain/model/snackbar/SnackbarMessage.kt index f86e7c8c6..574182d6a 100644 --- a/core/util/src/main/kotlin/de/davis/keygo/core/util/domain/model/snackbar/SnackbarMessage.kt +++ b/core/util/src/main/kotlin/de/davis/keygo/core/util/domain/model/snackbar/SnackbarMessage.kt @@ -4,7 +4,4 @@ import de.davis.keygo.core.util.presentation.UIText data class SnackbarMessage( val message: UIText, - val action: SnackbarAction? = null, - val onDismiss: () -> Unit = {}, ) - diff --git a/core/util/src/main/kotlin/de/davis/keygo/core/util/domain/snackbar/SnackbarManager.kt b/core/util/src/main/kotlin/de/davis/keygo/core/util/domain/snackbar/SnackbarManager.kt index 387d9a286..0df61a0df 100644 --- a/core/util/src/main/kotlin/de/davis/keygo/core/util/domain/snackbar/SnackbarManager.kt +++ b/core/util/src/main/kotlin/de/davis/keygo/core/util/domain/snackbar/SnackbarManager.kt @@ -2,14 +2,10 @@ package de.davis.keygo.core.util.domain.snackbar import de.davis.keygo.core.util.domain.model.snackbar.SnackbarMessage import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.StateFlow interface SnackbarManager { val oneShotEvents: Flow - val stickyMessage: StateFlow - fun sendMessage(message: SnackbarMessage) - fun reset() } diff --git a/core/util/src/main/kotlin/de/davis/keygo/core/util/presentation/snackbar/ObserveSnackbarEvents.kt b/core/util/src/main/kotlin/de/davis/keygo/core/util/presentation/snackbar/ObserveSnackbarEvents.kt index 9d9642755..0919bc206 100644 --- a/core/util/src/main/kotlin/de/davis/keygo/core/util/presentation/snackbar/ObserveSnackbarEvents.kt +++ b/core/util/src/main/kotlin/de/davis/keygo/core/util/presentation/snackbar/ObserveSnackbarEvents.kt @@ -2,15 +2,11 @@ package de.davis.keygo.core.util.presentation.snackbar import androidx.compose.material3.SnackbarDuration import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.SnackbarResult import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.platform.LocalContext -import de.davis.keygo.core.util.domain.model.snackbar.SnackbarMessage import de.davis.keygo.core.util.domain.snackbar.SnackbarManager import de.davis.keygo.core.util.presentation.ObserveAsEvents import de.davis.keygo.core.util.presentation.resolve -import kotlinx.coroutines.flow.filterNotNull @Composable fun SnackbarHandler( @@ -19,37 +15,13 @@ fun SnackbarHandler( ) { val context = LocalContext.current - suspend fun show(msg: SnackbarMessage) { - val text = msg.message.resolve(context) - val actionText = msg.action?.label?.resolve(context) - - val result = snackbarHostState.showSnackbar( - message = text, - actionLabel = actionText, - duration = SnackbarDuration.Short - ) - - when { - msg.action != null && result == SnackbarResult.ActionPerformed -> { - msg.action.onClick() - } - - else -> { - msg.onDismiss() - } - } - } - - // One-shot messages (errors): fire and forget, not replayed after rotation + // Fire and forget, not replayed after rotation. Nothing may hang a pending write off a + // snackbar's lifetime: a message that is dropped or replaced has to cost nothing but the + // message. ObserveAsEvents(snackbarManager.oneShotEvents, snackbarManager) { msg -> - show(msg) - } - - // Sticky messages (undo actions): replayed after rotation via StateFlow - LaunchedEffect(snackbarManager) { - snackbarManager.stickyMessage.filterNotNull().collect { msg -> - show(msg) - snackbarManager.reset() - } + snackbarHostState.showSnackbar( + message = msg.message.resolve(context), + duration = SnackbarDuration.Short, + ) } } diff --git a/core/util/src/test/kotlin/de/davis/keygo/core/util/data/snackbar/SnackbarManagerImplTest.kt b/core/util/src/test/kotlin/de/davis/keygo/core/util/data/snackbar/SnackbarManagerImplTest.kt index 8cfffbecc..e9eeb6a98 100644 --- a/core/util/src/test/kotlin/de/davis/keygo/core/util/data/snackbar/SnackbarManagerImplTest.kt +++ b/core/util/src/test/kotlin/de/davis/keygo/core/util/data/snackbar/SnackbarManagerImplTest.kt @@ -1,70 +1,41 @@ package de.davis.keygo.core.util.data.snackbar -import de.davis.keygo.core.util.domain.model.snackbar.SnackbarAction import de.davis.keygo.core.util.domain.model.snackbar.SnackbarMessage import de.davis.keygo.core.util.presentation.UIText -import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.flow.toList import kotlinx.coroutines.test.runTest import kotlin.test.Test import kotlin.test.assertEquals -import kotlin.test.assertNull class SnackbarManagerImplTest { private val manager = SnackbarManagerImpl() - private fun message(text: String, withAction: Boolean = false) = SnackbarMessage( - message = UIText.RawString(text), - action = if (withAction) SnackbarAction( - label = UIText.RawString("Undo"), - onClick = {} - ) else null - ) + private fun message(text: String) = SnackbarMessage(message = UIText.RawString(text)) @Test - fun `sendMessage buffers one-shot message without action`() = runTest { + fun `sendMessage buffers a message`() = runTest { val msg = message("hello") manager.sendMessage(msg) - val received = manager.oneShotEvents.first() - assertEquals(msg, received) + assertEquals(listOf(msg), manager.oneShotEvents.take(1).toList()) } @Test - fun `sendMessage sets sticky message with action`() { - val msg = message("hello", withAction = true) - - manager.sendMessage(msg) - - assertEquals(msg, manager.stickyMessage.value) - } - - @Test - fun `sticky message survives new collectors`() { - val msg = message("sticky", withAction = true) - manager.sendMessage(msg) - - // StateFlow replays to new collectors - assertEquals(msg, manager.stickyMessage.value) - } - - @Test - fun `reset clears sticky message`() { - val msg = message("sticky", withAction = true) - manager.sendMessage(msg) - manager.reset() - - assertNull(manager.stickyMessage.value) - } - - @Test - fun `reset does not affect one-shot messages`() = runTest { - val msg = message("error") - manager.sendMessage(msg) - manager.reset() - - val received = manager.oneShotEvents.first() - assertEquals(msg, received) + fun `messages sent back to back are all delivered in order`() = runTest { + val first = message("first") + val second = message("second") + val third = message("third") + + manager.sendMessage(first) + manager.sendMessage(second) + manager.sendMessage(third) + + assertEquals( + listOf(first, second, third), + manager.oneShotEvents.take(3).toList(), + ) } } diff --git a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/ItemListScreen.kt b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/ItemListScreen.kt index 81a34dcbe..36486d222 100644 --- a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/ItemListScreen.kt +++ b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/ItemListScreen.kt @@ -35,7 +35,7 @@ fun ItemListScreen( onCreateItemRequest: (VaultItemType) -> Unit, modifier: Modifier = Modifier, onItemLongClick: (ItemId) -> Unit = {}, - onItemDelete: (deleted: ItemId, firstItemId: ItemId?) -> Unit = { _, _ -> }, + onItemsDelete: (deleted: Set, firstItemId: ItemId?) -> Unit = { _, _ -> }, restrictedItemType: VaultItemType? = null, notFoundStrategy: NoItemStrategy = NoItemStrategy.ShowCreateNewItemCard, autoSelectFirst: Boolean = false, @@ -59,7 +59,7 @@ fun ItemListScreen( viewModel.onItemClick(uiState.items.first().id, forceSkipSelection = true) } - val currentOnItemDelete by rememberUpdatedState(onItemDelete) + val currentOnItemsDelete by rememberUpdatedState(onItemsDelete) ObserveAsEvents(flow = viewModel.event) { when (it) { is Event.ItemSelected -> { @@ -70,8 +70,8 @@ fun ItemListScreen( onItemLongClick(it.itemId) } - is Event.ItemDeleted -> { - currentOnItemDelete(it.itemId, it.firstItemId) + is Event.ItemsDeleted -> { + currentOnItemsDelete(it.itemIds, it.firstItemId) } } } @@ -107,7 +107,11 @@ fun ItemListScreen( onFilterAction = viewModel::onFilterAction, onItemClick = viewModel::onItemClick, onItemLongClick = viewModel::onItemLongClick, - onDelete = viewModel::onDelete, + onClearSelection = viewModel::onClearSelection, + onSelectAll = viewModel::onSelectAll, + onDeleteSelectedRequest = viewModel::onDeleteSelectedRequest, + onDismissDeleteConfirmation = viewModel::onDismissDeleteConfirmation, + onConfirmDeleteSelected = viewModel::onConfirmDeleteSelected, scrollBehavior = scrollBehavior, onVaultSelectorClick = viewModel::onVaultSelectorClick, onDismissVaultFlow = viewModel::onDismissVaultFlow, diff --git a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/ItemListViewModel.kt b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/ItemListViewModel.kt index 845408f00..6e982ee25 100644 --- a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/ItemListViewModel.kt +++ b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/ItemListViewModel.kt @@ -14,7 +14,6 @@ import de.davis.keygo.core.item.domain.repository.LoginRepository import de.davis.keygo.core.item.domain.usecase.ObserveAllTagsSortedUseCase import de.davis.keygo.core.item.generated.domain.model.VaultItemType import de.davis.keygo.core.util.combine -import de.davis.keygo.core.util.domain.snackbar.SnackbarManager import de.davis.keygo.feature.list_screen.domain.model.FilterState import de.davis.keygo.feature.list_screen.domain.usecase.FilterUseCase import de.davis.keygo.feature.list_screen.presentation.mapper.toAvailableFilterOptions @@ -24,11 +23,9 @@ import de.davis.keygo.feature.list_screen.presentation.model.FilterAction import de.davis.keygo.feature.list_screen.presentation.model.FilterBottomSheetState import de.davis.keygo.feature.list_screen.presentation.model.ListItemState import de.davis.keygo.feature.vault.domain.usecase.ObserveVaultsAndSelectionUseCase -import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview -import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow @@ -60,7 +57,6 @@ private val SEARCH_DEBOUNCE = 300.milliseconds internal class ItemListViewModel( @InjectedParam private val enableSelection: Boolean, @InjectedParam private val restrictedItemType: VaultItemType?, - private val snackbarManager: SnackbarManager, private val itemRepository: ItemRepository, private val filterUseCase: FilterUseCase, observeAllTags: ObserveAllTagsSortedUseCase, @@ -78,15 +74,9 @@ internal class ItemListViewModel( private val submittedSearchQuery = MutableStateFlow("") @OptIn(ExperimentalCoroutinesApi::class) - private val itemSource = submittedSearchQuery.flatMapLatest(::queryToItems) - - private val flaggedForDeletion = MutableStateFlow(setOf()) - private val nonDeletedItems = combine( - itemSource, - flaggedForDeletion - ) { items, flagged -> - items.filterNot { item -> item.id in flagged } - }.distinctUntilChanged() + private val itemSource = submittedSearchQuery + .flatMapLatest(::queryToItems) + .distinctUntilChanged() private val passwordScores = loginRepository.observePasswordScores() @@ -102,7 +92,7 @@ internal class ItemListViewModel( } private val filteredItems = combine( - nonDeletedItems, + itemSource, filterState, passwordScores, tagFilteredItemIds, @@ -113,6 +103,7 @@ internal class ItemListViewModel( private val selectedItemIds = MutableStateFlow(emptySet()) private val highlightedId = MutableStateFlow(null) private val _isVaultFlowVisible = MutableStateFlow(false) + private val _isDeleteConfirmationVisible = MutableStateFlow(false) @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) private val searchResults = snapshotFlow { searchTextFieldState.text } @@ -135,7 +126,8 @@ internal class ItemListViewModel( submittedSearchQuery, highlightedId, _isVaultFlowVisible, - ) { vaultsAndSel, items, searchResults, selectedIds, submittedSearchQuery, highlightedId, isVaultFlowVisible -> + _isDeleteConfirmationVisible, + ) { vaultsAndSel, items, searchResults, selectedIds, submittedSearchQuery, highlightedId, isVaultFlowVisible, isDeleteConfirmationVisible -> ListItemState( items = items, searchResults = searchResults, @@ -143,6 +135,7 @@ internal class ItemListViewModel( selectedItemIds = selectedIds, highlightedId = highlightedId, isVaultFlowVisible = isVaultFlowVisible, + isDeleteConfirmationVisible = isDeleteConfirmationVisible, vaults = vaultsAndSel.vaults, vaultContext = vaultsAndSel.selection, ) @@ -154,7 +147,7 @@ internal class ItemListViewModel( ) private val availableFilterOptions = combine( - nonDeletedItems, + itemSource, passwordScores, itemRepository.observeTagsByItem(), observeAllTags(), @@ -215,12 +208,12 @@ internal class ItemListViewModel( private fun Set.toggle(element: T): Set = if (element in this) this - element else this + element - private suspend fun queryToItems( + private fun queryToItems( query: String, forceSearchAllVaults: Boolean = false ): Flow> = (if (!forceSearchAllVaults && query.isBlank()) vaultSpecificItems - else flowOf(itemRepository.searchVaultItem(query, restrictedItemType))) + else itemRepository.searchVaultItem(query, restrictedItemType)) fun onSubmitQuery() { submittedSearchQuery.update { searchTextFieldState.text.toString() } @@ -239,31 +232,40 @@ internal class ItemListViewModel( submittedSearchQuery.update { "" } } - fun onDelete(itemId: ItemId) { - updateItemSelectionState(itemId, selected = false) - updateItemDeletionState(itemId, deleted = true) + fun onSelectAll() { + if (!enableSelection) return + + selectedItemIds.update { listItemState.value.items.mapTo(mutableSetOf()) { it.id } } + } + + fun onClearSelection() { + selectedItemIds.update { emptySet() } + } + + fun onDeleteSelectedRequest() { + if (selectedItemIds.value.isNotEmpty()) _isDeleteConfirmationVisible.update { true } + } + + fun onDismissDeleteConfirmation() { + _isDeleteConfirmationVisible.update { false } + } + + fun onConfirmDeleteSelected() { + _isDeleteConfirmationVisible.update { false } - val firstItemId = listItemState.value.items.firstOrNull()?.id - if (highlightedId.value == itemId) + val deleted = selectedItemIds.getAndUpdate { emptySet() } + if (deleted.isEmpty()) return + + // Read off the list still on screen: after the delete lands the flow has already dropped + // these rows, so the survivor has to be picked before the write. + val firstItemId = listItemState.value.items.firstOrNull { it.id !in deleted }?.id + if (highlightedId.value in deleted) highlightedId.update { firstItemId } - _event.trySend(Event.ItemDeleted(itemId, firstItemId)) - - snackbarManager.sendMessage( - ItemDeletedMessage( - onClick = { - updateItemDeletionState(itemId, deleted = false) - }, - onDismiss = { - viewModelScope.launch { - itemRepository.deleteItem(itemId) - - // Inside this coroutine to ensure it only runs after the deletion - updateItemDeletionState(itemId, deleted = false) - } - } - ) - ) + viewModelScope.launch { + itemRepository.deleteItems(deleted) + _event.trySend(Event.ItemsDeleted(deleted, firstItemId)) + } } @@ -292,22 +294,4 @@ internal class ItemListViewModel( } } - private fun updateItemDeletionState(id: ItemId, deleted: Boolean) { - flaggedForDeletion.update { currentDeletedIds -> - if (deleted) currentDeletedIds + id - else currentDeletedIds - id - } - } - - override fun onCleared() { - // Delete all flagged items, once the viewmodel is being cleared - val pendingDeletions = flaggedForDeletion.getAndUpdate { emptySet() } - if (pendingDeletions.isNotEmpty()) { - CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { - pendingDeletions.forEach { itemId -> - itemRepository.deleteItem(itemId) - } - } - } - } } diff --git a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/SnackbarMessages.kt b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/SnackbarMessages.kt deleted file mode 100644 index 61edbb463..000000000 --- a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/SnackbarMessages.kt +++ /dev/null @@ -1,19 +0,0 @@ -package de.davis.keygo.feature.list_screen.presentation - -import de.davis.keygo.core.util.domain.model.snackbar.SnackbarAction -import de.davis.keygo.core.util.domain.model.snackbar.SnackbarMessage -import de.davis.keygo.core.util.presentation.UIText -import de.davis.keygo.feature.list_screen.R - -@Suppress("FunctionName") -fun ItemDeletedMessage( - onClick: () -> Unit, - onDismiss: () -> Unit, -) = SnackbarMessage( - message = UIText.PluralsString(R.plurals.items_deleted, 1), - action = SnackbarAction( - label = UIText.ResourceString(R.string.undo), - onClick = onClick, - ), - onDismiss = onDismiss -) \ No newline at end of file diff --git a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/DeleteItemsDialog.kt b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/DeleteItemsDialog.kt new file mode 100644 index 000000000..5c1279788 --- /dev/null +++ b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/DeleteItemsDialog.kt @@ -0,0 +1,61 @@ +package de.davis.keygo.feature.list_screen.presentation.components + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.DeleteForever +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import de.davis.keygo.feature.list_screen.R + +@Composable +internal fun DeleteItemsDialog( + itemCount: Int, + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + confirmButton = { + TextButton( + onClick = onConfirm, + colors = ButtonDefaults.textButtonColors( + contentColor = MaterialTheme.colorScheme.error, + ), + ) { + Text(text = stringResource(R.string.delete)) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { + Text(text = stringResource(R.string.cancel)) + } + }, + icon = { + Icon(imageVector = Icons.Default.DeleteForever, contentDescription = null) + }, + title = { + Text( + text = pluralStringResource( + R.plurals.delete_items_title, + itemCount, + itemCount, + ) + ) + }, + text = { + Text( + text = pluralStringResource( + R.plurals.delete_items_message, + itemCount, + itemCount, + ) + ) + }, + ) +} diff --git a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/ItemListContent.kt b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/ItemListContent.kt index 575b37703..72bd7c66e 100644 --- a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/ItemListContent.kt +++ b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/ItemListContent.kt @@ -1,5 +1,6 @@ package de.davis.keygo.feature.list_screen.presentation.components +import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedContent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.ColumnScope @@ -72,7 +73,11 @@ internal fun ItemListContent( onFilterAction: (FilterAction) -> Unit, onItemClick: (ItemId, forceSkipSelection: Boolean) -> Unit, onItemLongClick: (ItemId) -> Unit, - onDelete: (ItemId) -> Unit, + onClearSelection: () -> Unit, + onSelectAll: () -> Unit, + onDeleteSelectedRequest: () -> Unit, + onDismissDeleteConfirmation: () -> Unit, + onConfirmDeleteSelected: () -> Unit, onVaultSelectorClick: () -> Unit, onDismissVaultFlow: () -> Unit, scrollBehavior: SearchBarScrollBehavior, @@ -103,14 +108,33 @@ internal fun ItemListContent( if (uiState.isVaultFlowVisible) VaultFlow(onDismiss = onDismissVaultFlow) + if (uiState.isDeleteConfirmationVisible) + DeleteItemsDialog( + itemCount = uiState.selectedItemIds.size, + onConfirm = onConfirmDeleteSelected, + onDismiss = onDismissDeleteConfirmation, + ) + + // Leaving a selection is what back means first, ahead of leaving the screen. + BackHandler(enabled = uiState.isSelectionActive, onBack = onClearSelection) + Scaffold( modifier = modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { - AppBarWithSearch( - state = searchBarState, - inputField = searchInputField, - scrollBehavior = scrollBehavior - ) + if (uiState.isSelectionActive) + SelectionTopBar( + selectedCount = uiState.selectedItemIds.size, + canDelete = enableDeletion, + onClearSelection = onClearSelection, + onSelectAll = onSelectAll, + onDeleteSelected = onDeleteSelectedRequest, + ) + else + AppBarWithSearch( + state = searchBarState, + inputField = searchInputField, + scrollBehavior = scrollBehavior + ) val searchResultContent: @Composable ColumnScope.() -> Unit = { val scope = rememberCoroutineScope() @@ -206,11 +230,9 @@ internal fun ItemListContent( KeyGoColumn( items = items, - onDelete = onDelete, onItemClick = { onItemClick(it, false) }, onItemLongClick = onItemLongClick, modifier = Modifier.padding(horizontal = 8.dp), - enableSwipeToDelete = enableDeletion, openedItemId = if (autoSelectFirst) uiState.highlightedId else null, selectedItemIds = uiState.selectedItemIds ) @@ -279,7 +301,11 @@ private fun ItemListContentPreview() { onFilterAction = {}, onItemClick = { _, _ -> }, onItemLongClick = {}, - onDelete = {}, + onClearSelection = {}, + onSelectAll = {}, + onDeleteSelectedRequest = {}, + onDismissDeleteConfirmation = {}, + onConfirmDeleteSelected = {}, onVaultSelectorClick = {}, onDismissVaultFlow = {}, scrollBehavior = scrollBehavior diff --git a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/SelectionTopBar.kt b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/SelectionTopBar.kt new file mode 100644 index 000000000..9cd72576e --- /dev/null +++ b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/SelectionTopBar.kt @@ -0,0 +1,65 @@ +package de.davis.keygo.feature.list_screen.presentation.components + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.SelectAll +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import de.davis.keygo.feature.list_screen.R + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun SelectionTopBar( + selectedCount: Int, + canDelete: Boolean, + onClearSelection: () -> Unit, + onSelectAll: () -> Unit, + onDeleteSelected: () -> Unit, + modifier: Modifier = Modifier, +) { + TopAppBar( + title = { + Text(text = stringResource(R.string.selected_count, selectedCount)) + }, + modifier = modifier, + navigationIcon = { + IconButton(onClick = onClearSelection) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = stringResource(R.string.clear_selection), + ) + } + }, + actions = { + IconButton(onClick = onSelectAll) { + Icon( + imageVector = Icons.Default.SelectAll, + contentDescription = stringResource(R.string.select_all), + ) + } + + if (canDelete) + IconButton(onClick = onDeleteSelected) { + Icon( + imageVector = Icons.Default.Delete, + contentDescription = stringResource(R.string.delete), + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.secondaryContainer, + titleContentColor = MaterialTheme.colorScheme.onSecondaryContainer, + navigationIconContentColor = MaterialTheme.colorScheme.onSecondaryContainer, + actionIconContentColor = MaterialTheme.colorScheme.onSecondaryContainer, + ), + ) +} diff --git a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/model/Event.kt b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/model/Event.kt index c49f06a71..c0987c731 100644 --- a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/model/Event.kt +++ b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/model/Event.kt @@ -6,5 +6,5 @@ internal sealed interface Event { data class ItemSelected(val itemId: ItemId) : Event data class ItemLongClicked(val itemId: ItemId) : Event - data class ItemDeleted(val itemId: ItemId, val firstItemId: ItemId?) : Event + data class ItemsDeleted(val itemIds: Set, val firstItemId: ItemId?) : Event } diff --git a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/model/ListItemState.kt b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/model/ListItemState.kt index 8e47add18..f33830b68 100644 --- a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/model/ListItemState.kt +++ b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/model/ListItemState.kt @@ -14,6 +14,9 @@ internal data class ListItemState( val selectedItemIds: Set = emptySet(), val highlightedId: ItemId? = null, val isVaultFlowVisible: Boolean = false, + val isDeleteConfirmationVisible: Boolean = false, val vaults: List = emptyList(), val vaultContext: VaultContext = VaultContext.NoSpecific, -) +) { + val isSelectionActive: Boolean get() = selectedItemIds.isNotEmpty() +} diff --git a/feature/list_screen/src/main/res/values/strings.xml b/feature/list_screen/src/main/res/values/strings.xml index ab1c3a9a3..f2fdd2062 100644 --- a/feature/list_screen/src/main/res/values/strings.xml +++ b/feature/list_screen/src/main/res/values/strings.xml @@ -2,12 +2,21 @@ Search your Vault - - 1 item deleted - %d items deleted + %d selected + Clear selection + Select all + Delete + Cancel + + + Delete item? + Delete %d items? - Undo + + This item will be permanently deleted. This cannot be undone. + These %d items will be permanently deleted. This cannot be undone. + Filter Sort order diff --git a/feature/list_screen/src/test/kotlin/de/davis/keygo/feature/list_screen/presentation/ItemListViewModelTest.kt b/feature/list_screen/src/test/kotlin/de/davis/keygo/feature/list_screen/presentation/ItemListViewModelTest.kt new file mode 100644 index 000000000..d0d650f24 --- /dev/null +++ b/feature/list_screen/src/test/kotlin/de/davis/keygo/feature/list_screen/presentation/ItemListViewModelTest.kt @@ -0,0 +1,274 @@ +package de.davis.keygo.feature.list_screen.presentation + +import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd +import de.davis.keygo.core.item.FakeItemRepository +import de.davis.keygo.core.item.FakeLoginRepository +import de.davis.keygo.core.item.FakeVaultContextRepository +import de.davis.keygo.core.item.FakeVaultRepository +import de.davis.keygo.core.item.domain.alias.ItemId +import de.davis.keygo.core.item.domain.alias.VaultId +import de.davis.keygo.core.item.domain.alias.newItemId +import de.davis.keygo.core.item.domain.alias.newVaultId +import de.davis.keygo.core.item.domain.model.KeyInformation +import de.davis.keygo.core.item.domain.model.Login +import de.davis.keygo.core.item.domain.model.Timestamp +import de.davis.keygo.core.item.domain.usecase.ObserveAllTagsSortedUseCase +import de.davis.keygo.core.util.domain.usecase.SortUseCase +import de.davis.keygo.feature.list_screen.domain.usecase.FilterUseCase +import de.davis.keygo.feature.vault.domain.usecase.ObserveVaultsAndSelectionUseCase +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Deletion is committed while the user is present, so these assert against what the repository + * actually holds afterwards rather than against anything still pending in the ViewModel. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class ItemListViewModelTest { + + private val dispatcher = StandardTestDispatcher() + + private val vaultId = newVaultId() + private val loginRepository = FakeLoginRepository() + private val itemRepository = FakeItemRepository(loginRepository) + private val vaultRepository = FakeVaultRepository() + private val vaultContextRepository = FakeVaultContextRepository() + private val sortUseCase = SortUseCase() + + @BeforeTest + fun setUp() = Dispatchers.setMain(dispatcher) + + @AfterTest + fun tearDown() = Dispatchers.resetMain() + + private fun viewModel(enableSelection: Boolean = true) = ItemListViewModel( + enableSelection = enableSelection, + restrictedItemType = null, + itemRepository = itemRepository, + filterUseCase = FilterUseCase(sortUseCase), + observeAllTags = ObserveAllTagsSortedUseCase(itemRepository, sortUseCase), + observeVaultsAndSelection = ObserveVaultsAndSelectionUseCase( + vaultRepository = vaultRepository, + vaultContextRepository = vaultContextRepository, + sortUseCase = sortUseCase, + ), + loginRepository = loginRepository, + ) + + private fun login(name: String, id: ItemId = newItemId(), vault: VaultId = vaultId) = Login( + id = id, + name = name, + username = null, + domainInfos = emptySet(), + passwordCredential = null, + totp = null, + passkeys = emptySet(), + note = null, + pinned = false, + vaultId = vault, + keyInformation = KeyInformation(byteArrayOf(), byteArrayOf()), + timestamp = Timestamp(), + ) + + private suspend fun storedIds(): Set = + itemRepository.observeLiteVaultItems().first().mapTo(mutableSetOf()) { it.id } + + /** + * The bug this flow replaced: each swipe hung its delete off a snackbar that the next swipe + * replaced, so every item after the first was hidden but never actually deleted. + */ + @Test + fun `deleting a whole selection removes every item in it`() = runTest(dispatcher) { + val first = login("First") + val second = login("Second") + val third = login("Third") + loginRepository.seed(first, second, third) + + val vm = viewModel() + vm.onItemLongClick(first.id) + vm.onItemClick(second.id) + vm.onItemClick(third.id) + + vm.onDeleteSelectedRequest() + vm.onConfirmDeleteSelected() + advanceUntilIdle() + + assertEquals(emptySet(), storedIds()) + } + + @Test + fun `deleting a selection leaves the items outside it alone`() = runTest(dispatcher) { + val doomed = login("Doomed") + val survivor = login("Survivor") + loginRepository.seed(doomed, survivor) + + val vm = viewModel() + vm.onItemLongClick(doomed.id) + vm.onDeleteSelectedRequest() + vm.onConfirmDeleteSelected() + advanceUntilIdle() + + assertEquals(setOf(survivor.id), storedIds()) + } + + @Test + fun `dismissing the confirmation deletes nothing and keeps the selection`() = + runTest(dispatcher) { + val item = login("Kept") + loginRepository.seed(item) + + val vm = viewModel() + backgroundScope.launchCollect(vm) + advanceUntilIdle() + + vm.onItemLongClick(item.id) + vm.onDeleteSelectedRequest() + vm.onDismissDeleteConfirmation() + advanceUntilIdle() + + assertEquals(setOf(item.id), storedIds()) + assertEquals(setOf(item.id), vm.listItemState.value.selectedItemIds) + assertFalse(vm.listItemState.value.isDeleteConfirmationVisible) + } + + @Test + fun `confirming clears the selection so a second confirm deletes nothing more`() = + runTest(dispatcher) { + val doomed = login("Doomed") + val survivor = login("Survivor") + loginRepository.seed(doomed, survivor) + + val vm = viewModel() + backgroundScope.launchCollect(vm) + advanceUntilIdle() + + vm.onItemLongClick(doomed.id) + vm.onDeleteSelectedRequest() + vm.onConfirmDeleteSelected() + advanceUntilIdle() + + vm.onConfirmDeleteSelected() + advanceUntilIdle() + + assertEquals(setOf(survivor.id), storedIds()) + assertEquals(emptySet(), vm.listItemState.value.selectedItemIds) + } + + @Test + fun `requesting a delete with nothing selected does not open the dialog`() = + runTest(dispatcher) { + loginRepository.seed(login("Untouched")) + + val vm = viewModel() + backgroundScope.launchCollect(vm) + advanceUntilIdle() + + vm.onDeleteSelectedRequest() + advanceUntilIdle() + + assertFalse(vm.listItemState.value.isDeleteConfirmationVisible) + } + + @Test + fun `select all selects every listed item`() = runTest(dispatcher) { + val items = listOf(login("A"), login("B"), login("C")) + loginRepository.seed(*items.toTypedArray()) + + val vm = viewModel() + backgroundScope.launchCollect(vm) + advanceUntilIdle() + + vm.onSelectAll() + advanceUntilIdle() + + assertEquals(items.mapTo(mutableSetOf()) { it.id }, vm.listItemState.value.selectedItemIds) + assertTrue(vm.listItemState.value.isSelectionActive) + } + + @Test + fun `select all does nothing on a screen that does not allow selection`() = + runTest(dispatcher) { + loginRepository.seed(login("A")) + + val vm = viewModel(enableSelection = false) + backgroundScope.launchCollect(vm) + advanceUntilIdle() + + vm.onSelectAll() + advanceUntilIdle() + + assertEquals(emptySet(), vm.listItemState.value.selectedItemIds) + } + + /** + * The search branch feeds off a live query, so the delete has to reach the results on its own. + * Pins that: a snapshot source would leave the deleted rows on screen until the query changed. + */ + @Test + fun `deleting while a search is submitted drops the rows from the results`() = + runTest(dispatcher) { + val doomed = login("Doomed") + val survivor = login("Survivor") + loginRepository.seed(doomed, survivor) + + val vm = viewModel() + backgroundScope.launchCollect(vm) + vm.searchTextFieldState.setTextAndPlaceCursorAtEnd("o") + vm.onSubmitQuery() + advanceUntilIdle() + + assertEquals( + setOf(doomed.id, survivor.id), + vm.listItemState.value.items.mapTo(mutableSetOf()) { it.id }, + ) + + vm.onItemLongClick(doomed.id) + vm.onDeleteSelectedRequest() + vm.onConfirmDeleteSelected() + advanceUntilIdle() + + assertEquals( + setOf(survivor.id), + vm.listItemState.value.items.mapTo(mutableSetOf()) { it.id }, + ) + } + + @Test + fun `clearing the selection leaves every item in place`() = runTest(dispatcher) { + val item = login("Kept") + loginRepository.seed(item) + + val vm = viewModel() + backgroundScope.launchCollect(vm) + advanceUntilIdle() + + vm.onItemLongClick(item.id) + vm.onClearSelection() + advanceUntilIdle() + + assertEquals(setOf(item.id), storedIds()) + assertEquals(emptySet(), vm.listItemState.value.selectedItemIds) + } +} + +/** + * `listItemState` is shared with `WhileSubscribed`, so a test that reads items back out of it + * needs a live subscriber first, otherwise it only ever sees the initial empty state. + */ +private fun CoroutineScope.launchCollect(vm: ItemListViewModel) { + launch { vm.listItemState.collect { } } +} From bc8c57fc438ea9e19a7b0a393dffe97945f0e21c Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sat, 22 Aug 2026 21:58:14 +0200 Subject: [PATCH 2/3] fix: stocky header positon --- .../core/ui/components/KeyGoLazyColumn.kt | 99 ++++++++++++++----- 1 file changed, 77 insertions(+), 22 deletions(-) diff --git a/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/KeyGoLazyColumn.kt b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/KeyGoLazyColumn.kt index 422c183c0..4bec6c73b 100644 --- a/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/KeyGoLazyColumn.kt +++ b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/KeyGoLazyColumn.kt @@ -4,10 +4,12 @@ import androidx.compose.animation.animateColorAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyItemScope import androidx.compose.foundation.lazy.itemsIndexed @@ -28,6 +30,7 @@ import androidx.compose.runtime.Stable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -36,6 +39,7 @@ import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInParent +import androidx.compose.ui.layout.positionInWindow import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview @@ -43,6 +47,7 @@ import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import de.davis.keygo.core.item.generated.domain.model.VaultItemType import de.davis.keygo.core.item.generated.presentation.presentation +import kotlin.math.roundToInt sealed interface HeaderContent { data class Letter(val char: Char) : HeaderContent @@ -56,6 +61,11 @@ data class KeyGoColumnItem( val itemType: VaultItemType, ) +/** + * The item the sticky header currently belongs to: [index] plus its [top] within the column. + */ +private data class StickyAnchor(val index: Int, val top: Int) + @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable fun KeyGoColumn( @@ -67,12 +77,42 @@ fun KeyGoColumn( selectedItemIds: Set = emptySet(), ) { val listState = rememberLazyListState() + val density = LocalDensity.current + + // The app bar above this column collapses away while scrolling, so the column can reach into + // the status bar. Everything sticky is anchored below the status bar rather than at the very + // top of the column, which would draw it behind the status bar. + val statusBarTop = WindowInsets.statusBars.getTop(density) + var columnTopInWindow by remember { mutableIntStateOf(statusBarTop) } + val stickyTop by remember(statusBarTop) { + derivedStateOf { (statusBarTop - columnTopInWindow).coerceAtLeast(0) } + } + + // The first item reaching below the anchor owns the sticky header. With no status bar to + // avoid this is exactly the first visible item. + val anchor by remember(listState, stickyTop) { + derivedStateOf { + val info = listState.layoutInfo.visibleItemsInfo.firstOrNull { + it.offset + it.size > stickyTop + } + + StickyAnchor( + index = info?.index ?: listState.firstVisibleItemIndex, + top = info?.offset ?: 0, + ) + } + } + val anchorIndex by remember(anchor) { derivedStateOf { anchor.index } } @Composable fun containerColorForId(id: ID): Color = if (id == openedItemId) OpenedContainerColor else ContainerColor - Box(modifier = modifier.clipToBounds()) { + Box( + modifier = modifier + .clipToBounds() + .onGloballyPositioned { columnTopInWindow = it.positionInWindow().y.roundToInt() } + ) { LazyColumn( modifier = Modifier.fillMaxSize(), state = listState, @@ -105,11 +145,21 @@ fun KeyGoColumn( .padding(bottom = bottomPadding) .expressiveAnimateItem(), leadingContent = { - val isFirstVisibleItem by remember(index) { - derivedStateOf { listState.firstVisibleItemIndex == index } + // The anchor row's letter is the sticky one. Below the anchor a group + // announces itself on its first row as usual; above it, a group that is + // on its way out rides its letter off the screen on its last row. + val showsHeader by remember(index, isFirst, isLast, anchorIndex) { + derivedStateOf { + val anchor = anchorIndex + when { + index > anchor -> isFirst + index < anchor -> isLast + else -> false + } + } } - if (isFirst && !isFirstVisibleItem) { + if (showsHeader) { KeyGoInlineHeader( header = item.header, color = contentColorFor(containerColorForId(id)) @@ -131,41 +181,46 @@ fun KeyGoColumn( // ----------- HEADER ----------- if (items.isEmpty()) return - val stickyHeader by remember(items) { + val stickyHeader by remember(anchor, items) { derivedStateOf { - if (listState.firstVisibleItemIndex < items.size) - items[listState.firstVisibleItemIndex].header - else HeaderContent.Letter(' ') + items.getOrNull(anchor.index)?.header ?: HeaderContent.Letter(' ') } } - val density = LocalDensity.current - val headerOffset by remember(listState, items, density) { + val headerOffset by remember(anchor, stickyTop, items, density) { derivedStateOf { val offset = with(density) { IntOffset(16.dp.roundToPx(), (10.dp + 6.dp).roundToPx()) } - val index = listState.firstVisibleItemIndex - if (index in items.indices && items.isLastInGroup(index)) - offset.copy(y = offset.y - listState.firstVisibleItemScrollOffset) - else offset + val (index, top) = anchor + val pinned = stickyTop + + // The last item of a group takes its header with it instead of holding it pinned. + val headerTop = if (index in items.indices && items.isLastInGroup(index)) + minOf(pinned, top) + else pinned + + offset.copy(y = offset.y + headerTop) } } var headerPositionY by remember { mutableFloatStateOf(0f) } - val idBehindHeader by remember(listState, items) { + // headerPositionY is in column coordinates, so both sides are shifted back to the + // anchor to tell whether the header has drifted over the next item. + val idBehindHeader by remember(anchor, stickyTop, items, headerOffset) { derivedStateOf { - val visibleItemIdx = listState.firstVisibleItemIndex + val (index, top) = anchor + val pinned = stickyTop val id = if ( - listState.firstVisibleItemScrollOffset >= headerPositionY && - headerOffset.y >= 0 && - visibleItemIdx + 1 in items.indices - ) visibleItemIdx + 1 - else visibleItemIdx + pinned - top >= headerPositionY - pinned && + headerOffset.y >= pinned && + index + 1 in items.indices + ) index + 1 + else index - items[id].id + items[id.coerceIn(items.indices)].id } } From 62d32942cd26f963cf03f099fad9985f3425362d Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sat, 22 Aug 2026 22:52:21 +0200 Subject: [PATCH 3/3] feat: add content padding --- .../keygo/core/ui/components/KeyGoLazyColumn.kt | 15 ++++++++++++--- .../presentation/components/ItemListContent.kt | 7 ++++++- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/KeyGoLazyColumn.kt b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/KeyGoLazyColumn.kt index 4bec6c73b..5cc9f5a53 100644 --- a/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/KeyGoLazyColumn.kt +++ b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/components/KeyGoLazyColumn.kt @@ -3,8 +3,10 @@ package de.davis.keygo.core.ui.components import androidx.compose.animation.animateColorAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.calculateStartPadding import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding @@ -41,6 +43,7 @@ import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.layout.positionInWindow import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.IntOffset @@ -73,11 +76,14 @@ fun KeyGoColumn( onItemClick: (ID) -> Unit, onItemLongClick: (ID) -> Unit, modifier: Modifier = Modifier, + contentPadding: PaddingValues = PaddingValues(horizontal = 8.dp), openedItemId: ID? = null, selectedItemIds: Set = emptySet(), ) { val listState = rememberLazyListState() val density = LocalDensity.current + val layoutDirection = LocalLayoutDirection.current + val headerStart = HeaderStartPadding + contentPadding.calculateStartPadding(layoutDirection) // The app bar above this column collapses away while scrolling, so the column can reach into // the status bar. Everything sticky is anchored below the status bar rather than at the very @@ -116,7 +122,8 @@ fun KeyGoColumn( LazyColumn( modifier = Modifier.fillMaxSize(), state = listState, - verticalArrangement = Arrangement.spacedBy(ItemVerticalPadding) + contentPadding = contentPadding, + verticalArrangement = Arrangement.spacedBy(ItemVerticalPadding), ) { itemsIndexed( items, @@ -187,10 +194,10 @@ fun KeyGoColumn( } } - val headerOffset by remember(anchor, stickyTop, items, density) { + val headerOffset by remember(anchor, stickyTop, items, density, headerStart) { derivedStateOf { val offset = with(density) { - IntOffset(16.dp.roundToPx(), (10.dp + 6.dp).roundToPx()) + IntOffset(headerStart.roundToPx(), (10.dp + 6.dp).roundToPx()) } val (index, top) = anchor @@ -294,6 +301,8 @@ private fun KeyGoInlineHeader( @Stable private fun Modifier.headerSize() = this.size(40.dp) +private val HeaderStartPadding = 16.dp + @OptIn(ExperimentalMaterial3ExpressiveApi::class) val ItemVerticalPadding = ListItemDefaults.SegmentedGap diff --git a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/ItemListContent.kt b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/ItemListContent.kt index 72bd7c66e..2252e9721 100644 --- a/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/ItemListContent.kt +++ b/feature/list_screen/src/main/kotlin/de/davis/keygo/feature/list_screen/presentation/components/ItemListContent.kt @@ -4,6 +4,7 @@ import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedContent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding @@ -232,7 +233,11 @@ internal fun ItemListContent( items = items, onItemClick = { onItemClick(it, false) }, onItemLongClick = onItemLongClick, - modifier = Modifier.padding(horizontal = 8.dp), + contentPadding = PaddingValues( + start = 8.dp, + end = 8.dp, + bottom = 96.dp, + ), openedItemId = if (autoSelectFirst) uiState.highlightedId else null, selectedItemIds = uiState.selectedItemIds )