INTEGRATION.md

16.7 KB · raw

rendered · source

1# D12 — Context Menu + Multi-Select in VaultListScreen — INTEGRATION23Wires the long-press context menu, undo-snackbar soft delete, and multi-select4batch delete into `VaultListScreen`. **D3 also edits this screen** (tag filter5strip + row chips); every block below is self-contained with quoted anchors so6the two merges don't collide.78## Files in this draft (copy as-is into `ui/vault/`)910- `ContextMenuSheet.kt` → `app/src/main/java/com/peachpasswords/ui/vault/ContextMenuSheet.kt`11  - public `ContextMenuSheet(...)`. Same package, so no import needed from VaultListScreen.12- `MultiSelectUi.kt` → `app/src/main/java/com/peachpasswords/ui/vault/MultiSelectUi.kt`13  - public `MultiSelectCheckbox(checked, modifier)` and `MultiSelectTopBar(count, onDelete, onCancel)`.1415Both are in package `com.peachpasswords.ui.vault`. No nav routes are added (Edit16reuses the existing `PeachNav.EntryEdit(id)`). No new gradle deps.1718---1920## 1. VaultRepository — no new methods required2122The repo already has everything D12 needs (verified in `VaultRepository.kt`):2324- `suspend fun deleteEntry(id: String)` — soft delete (writes a tombstone). Use this for `softDelete`.25- `suspend fun restoreEntry(id: String)` — clears the tombstone. Use for UNDO.2627There is **no** `softDelete`/`batchSoftDelete`/`restoreEntry` overload to add at the28repo layer. The VM wraps `deleteEntry` under the names the spec uses. Batch delete29is just a loop over `deleteEntry` (each call takes the mutex independently; that is30fine — there is no `deleteEntries(ids)` bulk method and adding one is unnecessary).3132> If a true bulk method is preferred later, the reference signature would be:33> ```kotlin34> // VaultRepository35> suspend fun deleteEntries(ids: Collection<String>) = mutex.withLock {36>     requireUnlocked()37>     val rollback = entryList.toMutableList()38>     for (id in ids) {39>         val idx = entryList.indexOfFirst { it.id == id && it.deletedAt == null }40>         if (idx == -1) continue41>         val cur = entryList[idx]42>         val stamp = VaultCrypto.monotonicEntryTimestamp(cur.modifiedAt)43>         entryList[idx] = cur.copy(deletedAt = stamp, modifiedAt = stamp)44>     }45>     persistOrRollback(rollback)46> }47> ```48> Not required for this item — the VM loop below is sufficient.4950---5152## 2. VaultListViewModel — state + methods to add5354Add these to `VaultListViewModel` (it already injects `vault: VaultRepository`55and `appContext`). New imports needed: none beyond what is already imported56(`MutableStateFlow`, `asStateFlow`, `launch`, `VaultEntry`, `TOTPGenerator` is57*not* imported — add `import com.peachpasswords.vault.TOTPGenerator` and58`import com.peachpasswords.haptics.PeachHaptics` is NOT needed here; haptics for59copy fire in the composable. Add `import android.content.ClipData`/`ClipboardManager`/60`Context` are already imported).6162```kotlin63// ── Multi-select ────────────────────────────────────────────────────────64private val _isMultiSelectMode = MutableStateFlow(false)65val isMultiSelectMode: StateFlow<Boolean> = _isMultiSelectMode.asStateFlow()6667private val _selectedIds = MutableStateFlow<Set<String>>(emptySet())68val selectedIds: StateFlow<Set<String>> = _selectedIds.asStateFlow()6970/** Long-press entry point: select the entry AND enter multi-select mode. */71fun enterMultiSelect(id: String) {72    _isMultiSelectMode.value = true73    _selectedIds.value = setOf(id)74}7576fun toggleSelected(id: String) {77    val next = _selectedIds.value.toMutableSet()78    if (!next.add(id)) next.remove(id)79    _selectedIds.value = next80    // Tapping the last selection off does not auto-exit; "Cancel" exits.81}8283fun exitMultiSelect() {84    _isMultiSelectMode.value = false85    _selectedIds.value = emptySet()86}8788// ── Soft delete + undo ──────────────────────────────────────────────────89/**90 * One-shot undo event for the snackbar. Carries the label to show and the ids91 * to restore. Consumed by the composable after it shows the snackbar.92 */93data class UndoEvent(val message: String, val ids: List<String>)9495private val _undoEvent = MutableStateFlow<UndoEvent?>(null)96val undoEvent: StateFlow<UndoEvent?> = _undoEvent.asStateFlow()97fun consumeUndoEvent() { _undoEvent.value = null }9899/** Soft-delete one entry and raise the "[name] moved to trash" undo event. */100fun softDelete(entry: VaultEntry) {101    viewModelScope.launch {102        runCatching { vault.deleteEntry(entry.id) }103        _undoEvent.value = UndoEvent("${entry.title} moved to trash", listOf(entry.id))104    }105}106107/** Batch soft-delete the current selection, exit mode, raise "[N] entries…". */108fun batchSoftDelete() {109    val ids = _selectedIds.value.toList()110    if (ids.isEmpty()) return111    viewModelScope.launch {112        ids.forEach { id -> runCatching { vault.deleteEntry(id) } }113        exitMultiSelect()114        _undoEvent.value = UndoEvent("${ids.size} entries moved to trash", ids)115    }116}117118/** UNDO action: restore every soft-deleted id from the snackbar event. */119fun restoreEntries(ids: List<String>) {120    viewModelScope.launch { ids.forEach { id -> runCatching { vault.restoreEntry(id) } } }121}122123// ── Context-menu copy helpers (reuse existing copyPassword pattern) ──────124private fun copyText(value: String?) {125    val v = value?.takeIf { it.isNotEmpty() } ?: return126    val cm = appContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager127    cm.setPrimaryClip(ClipData.newPlainText("peach", v))128}129130fun copyUsername(entry: VaultEntry) = copyText(entry.username ?: entry.email)131132/** Copy the LIVE TOTP code, never the stored seed (mirrors EntryDetailViewModel). */133fun copyTotp(entry: VaultEntry) {134    val seed = entry.totp ?: return135    copyText(TOTPGenerator.generateCode(seed))136}137```138139Note: `copyPassword(entry)` already exists on the VM (used by swipe-copy) — the140context menu reuses it directly.141142---143144## 3. VaultListScreen — composable wiring145146### 3a. New imports147148```kotlin149import androidx.compose.material3.SnackbarHost150import androidx.compose.material3.SnackbarHostState151import androidx.compose.material3.SnackbarResult152import androidx.compose.material3.Snackbar153import androidx.compose.runtime.LaunchedEffect154import androidx.compose.runtime.mutableStateOf155import androidx.compose.runtime.setValue156import androidx.compose.runtime.rememberCoroutineScope157import androidx.compose.foundation.layout.Box158import androidx.compose.ui.platform.LocalView159```160(`Box`, `LocalContext`, `getValue`, `remember` are already imported.)161162### 3b. Collect new state + set up snackbar/long-press plumbing163164Anchor — top of `VaultListScreen` body, the existing `collectAsState` block:165166```kotlin167    val entries by vm.entries.collectAsState()168    val sort by vm.sort.collectAsState()169    val search by vm.search.collectAsState()170    val total by vm.totalCount.collectAsState()171    val flashId by vm.flashId.collectAsState()172```173174Add immediately after it:175176```kotlin177    val isMultiSelect by vm.isMultiSelectMode.collectAsState()178    val selectedIds by vm.selectedIds.collectAsState()179    val undoEvent by vm.undoEvent.collectAsState()180    val snackbarHostState = remember { SnackbarHostState() }181    var menuEntry by remember { mutableStateOf<VaultEntry?>(null) }182183    // Drain VM undo events into the snackbar host; UNDO restores the ids.184    LaunchedEffect(undoEvent) {185        val ev = undoEvent ?: return@LaunchedEffect186        vm.consumeUndoEvent()187        val result = snackbarHostState.showSnackbar(188            message = ev.message,189            actionLabel = "UNDO",190            duration = androidx.compose.material3.SnackbarDuration.Short, // ~4s; spec asks 5s191        )192        if (result == SnackbarResult.ActionPerformed) vm.restoreEntries(ev.ids)193    }194```195196> 5s auto-dismiss: `SnackbarDuration.Short` is ~4s and `.Long` ~10s. If exactly 5s197> is required, omit `duration` and use a manual `delay(5000)` race, or accept Short.198> Recommend Short for platform consistency.199200### 3c. Wrap the screen so the snackbar host overlays, and swap the top bar201202Anchor — the existing root of the screen:203204```kotlin205    ShellBackground {206        Column(Modifier.fillMaxSize()) {207            TopBar(208                onSettings = { onNavigate(PeachNav.Settings) },209                onAdd = { onNavigate(PeachNav.EntryEdit(null)) },210            )211```212213Replace the `ShellBackground { Column(...) {` opening and the `TopBar(...)` call with:214215```kotlin216    ShellBackground {217        Box(Modifier.fillMaxSize()) {218        Column(Modifier.fillMaxSize()) {219            if (isMultiSelect) {220                MultiSelectTopBar(221                    count = selectedIds.size,222                    onDelete = { vm.batchSoftDelete() },223                    onCancel = { vm.exitMultiSelect() },224                )225            } else {226                TopBar(227                    onSettings = { onNavigate(PeachNav.Settings) },228                    onAdd = { onNavigate(PeachNav.EntryEdit(null)) },229                )230            }231```232233Then anchor — the closing of the screen:234235```kotlin236                item {237                    NewEntryRow(onClick = { onNavigate(PeachNav.EntryEdit(null)) })238                    Spacer(Modifier.navigationBarsPadding())239                }240            }241        }242    }243}244```245246Replace with (adds the snackbar host + closes the new Box):247248```kotlin249                item {250                    NewEntryRow(onClick = { onNavigate(PeachNav.EntryEdit(null)) })251                    Spacer(Modifier.navigationBarsPadding())252                }253            }254        }255        SnackbarHost(256            hostState = snackbarHostState,257            modifier = Modifier258                .align(Alignment.BottomCenter)259                .navigationBarsPadding(),260        ) { data ->261            // Peach-styled snackbar: glass panel, accent UNDO label.262            Snackbar(263                containerColor = PeachColors.SurfaceElevated,264                contentColor = PeachColors.T0,265                actionContentColor = LocalPeachAccent.current,266                snackbarData = data,267            )268        }269        } // Box270    }271272    menuEntry?.let { e ->273        ContextMenuSheet(274            entry = e,275            onCopyPassword = { vm.copyPassword(e); PeachHaptics.onCopy(view) },276            onCopyUsername = { vm.copyUsername(e); PeachHaptics.onCopy(view) },277            onCopyTotp = { vm.copyTotp(e); PeachHaptics.onCopy(view) },278            onEdit = { onNavigate(PeachNav.EntryEdit(e.id)) },279            onMoveToTrash = { vm.softDelete(e) },280            onDismiss = { menuEntry = null },281        )282    }283}284```285286For `PeachHaptics.onCopy(view)` add `val view = LocalView.current` near the top of287`VaultListScreen` (and import `com.peachpasswords.haptics.PeachHaptics`,288`androidx.compose.ui.platform.LocalView`). `LocalPeachAccent` and `PeachColors`289are already imported.290291### 3d. EntryRow — long-press + multi-select hooks292293The `items(...)` call needs the new params threaded through. Anchor:294295```kotlin296                items(entries, key = { it.id }) { entry ->297                    EntryRow(298                        entry = entry,299                        flashing = flashId == entry.id,300                        canSwipeCopy = vm.canSwipeCopy(entry),301                        onTap = { onNavigate(PeachNav.EntryDetail(entry.id)) },302                        onSwipeCopy = { vm.copyPassword(entry) },303                    )304                }305```306307Replace with:308309```kotlin310                items(entries, key = { it.id }) { entry ->311                    EntryRow(312                        entry = entry,313                        flashing = flashId == entry.id,314                        canSwipeCopy = vm.canSwipeCopy(entry) && !isMultiSelect,315                        multiSelect = isMultiSelect,316                        selected = entry.id in selectedIds,317                        onTap = {318                            if (isMultiSelect) vm.toggleSelected(entry.id)319                            else onNavigate(PeachNav.EntryDetail(entry.id))320                        },321                        onLongPress = {322                            if (isMultiSelect) vm.toggleSelected(entry.id)323                            else menuEntry = entry324                        },325                        onSwipeCopy = { vm.copyPassword(entry) },326                    )327                }328```329330> Spec offers two long-press behaviours: (a) open context menu, (b) enter331> multi-select. This wiring uses (a) — long-press opens the menu, and the menu's332> "Move to trash" handles single delete. To make long-press *enter multi-select*333> instead, change `onLongPress` to `{ vm.enterMultiSelect(entry.id) }` and add a334> "Select" button to the top bar that opens the menu, OR keep both: short menu has335> a "Select" row. Recommend (a) as primary; `enterMultiSelect` is provided on the336> VM if you want long-press → multi-select. Pick one and keep it consistent.337338### 3e. EntryRow signature + body changes339340Anchor — the existing `EntryRow` signature and the `pointerInput`/`clickable` block:341342```kotlin343@Composable344private fun EntryRow(345    entry: VaultEntry,346    flashing: Boolean,347    canSwipeCopy: Boolean,348    onTap: () -> Unit,349    onSwipeCopy: () -> Unit,350) {351```352353Replace the signature with:354355```kotlin356@Composable357private fun EntryRow(358    entry: VaultEntry,359    flashing: Boolean,360    canSwipeCopy: Boolean,361    multiSelect: Boolean,362    selected: Boolean,363    onTap: () -> Unit,364    onLongPress: () -> Unit,365    onSwipeCopy: () -> Unit,366) {367```368369Inside `EntryRow`, the existing swipe `pointerInput` block stays. Add a second370`pointerInput` for the 500ms long-press with haptic. Anchor — the existing371`.clickable(...)` line on the row `Modifier`:372373```kotlin374            .clickable(interactionSource = interaction, indication = null, onClick = onTap)375            .padding(horizontal = 16.dp, vertical = 9.dp),376```377378Insert a long-press detector *before* the `.clickable(...)` line:379380```kotlin381            .pointerInput(entry.id, multiSelect) {382                detectTapGestures(383                    onLongPress = {384                        PeachHaptics.onLongPress(context)385                        onLongPress()386                    },387                )388            }389            .clickable(interactionSource = interaction, indication = null, onClick = onTap)390            .padding(horizontal = 16.dp, vertical = 9.dp),391```392393`detectTapGestures(onLongPress=...)` uses Compose's default long-press timeout394(~400–500ms via `viewConfiguration.longPressTimeoutMillis`), satisfying the 500ms395spec without a manual timer. Imports to add to VaultListScreen:396`import androidx.compose.foundation.gestures.detectTapGestures`. `context` and397`PeachHaptics` are already in scope inside `EntryRow` (`context = LocalContext.current`,398PeachHaptics already imported).399400Finally, render the checkbox at the row's leading edge in multi-select. Anchor —401the first child of the row `Row { ... }`:402403```kotlin404        FaviconInitials(source = entry.url ?: entry.title, size = 26.dp)405```406407Replace with:408409```kotlin410        if (multiSelect) {411            MultiSelectCheckbox(checked = selected)412        }413        FaviconInitials(source = entry.url ?: entry.title, size = 26.dp)414```415416(The row `Arrangement.spacedBy(10.dp)` already spaces the checkbox from the favicon.)417418---419420## 4. Assumptions / risks421422- **No new repo methods.** `deleteEntry`/`restoreEntry` already exist and match the423  spec's `softDelete`/`restoreEntry` semantics (soft tombstone + restore). Batch is424  a VM-level loop; each `deleteEntry` takes the mutex separately — correct, just N425  writes. Add `deleteEntries(ids)` only if profiling shows the N writes matter.426- **TOTP copy** reuses `TOTPGenerator.generateCode(seed)` (the same call427  `EntryDetailViewModel.copyTotp` uses), copying the live 6-digit code, not the seed.428- **Snackbar duration**: `SnackbarDuration.Short` ≈ 4s, not the spec's exact 5s. See429  note in 3b; recommend Short for consistency, or manual timing if 5s is mandatory.430- **Long-press behaviour** is a one-or-the-other design choice (menu vs. enter431  multi-select). Draft wires menu-first and provides `enterMultiSelect` on the VM432  for the alternative. Orchestrator picks one.433- **D3 coexistence**: D3 inserts a tag filter strip *between SearchBar and SortBar*434  and adds row chips inside `EntryRow`'s `Column`. None of D12's anchors (top bar,435  the row's leading checkbox / long-press modifier, the snackbar host Box, the436  `items` lambda params) overlap with D3's insertion points, so the two merge437  cleanly. Both extend the `EntryRow` signature — when merging, combine the added438  params into one signature rather than applying each replacement blindly.439- **FLAG_SECURE / clipboard auto-clear**: copy uses the same plain440  `ClipboardManager.setPrimaryClip` the VM already uses for swipe-copy; no new441  secure-clip handling is introduced (matches existing behaviour).