INTEGRATION.md

16.7 KB · raw

rendered · source

D12 — Context Menu + Multi-Select in VaultListScreen — INTEGRATION

Wires the long-press context menu, undo-snackbar soft delete, and multi-select batch delete into VaultListScreen. D3 also edits this screen (tag filter strip + row chips); every block below is self-contained with quoted anchors so the two merges don't collide.

Files in this draft (copy as-is into ui/vault/)

Both are in package com.peachpasswords.ui.vault. No nav routes are added (Edit reuses the existing PeachNav.EntryEdit(id)). No new gradle deps.


1. VaultRepository — no new methods required

The repo already has everything D12 needs (verified in VaultRepository.kt):

There is no softDelete/batchSoftDelete/restoreEntry overload to add at the repo layer. The VM wraps deleteEntry under the names the spec uses. Batch delete is just a loop over deleteEntry (each call takes the mutex independently; that is fine — there is no deleteEntries(ids) bulk method and adding one is unnecessary).

If a true bulk method is preferred later, the reference signature would be:

// VaultRepository
suspend fun deleteEntries(ids: Collection<String>) = mutex.withLock {
    requireUnlocked()
    val rollback = entryList.toMutableList()
    for (id in ids) {
        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt == null }
        if (idx == -1) continue
        val cur = entryList[idx]
        val stamp = VaultCrypto.monotonicEntryTimestamp(cur.modifiedAt)
        entryList[idx] = cur.copy(deletedAt = stamp, modifiedAt = stamp)
    }
    persistOrRollback(rollback)
}

Not required for this item — the VM loop below is sufficient.


2. VaultListViewModel — state + methods to add

Add these to VaultListViewModel (it already injects vault: VaultRepository and appContext). New imports needed: none beyond what is already imported (MutableStateFlow, asStateFlow, launch, VaultEntry, TOTPGenerator is not imported — add import com.peachpasswords.vault.TOTPGenerator and import com.peachpasswords.haptics.PeachHaptics is NOT needed here; haptics for copy fire in the composable. Add import android.content.ClipData/ClipboardManager/ Context are already imported).

// ── Multi-select ────────────────────────────────────────────────────────
private val _isMultiSelectMode = MutableStateFlow(false)
val isMultiSelectMode: StateFlow<Boolean> = _isMultiSelectMode.asStateFlow()

private val _selectedIds = MutableStateFlow<Set<String>>(emptySet())
val selectedIds: StateFlow<Set<String>> = _selectedIds.asStateFlow()

/** Long-press entry point: select the entry AND enter multi-select mode. */
fun enterMultiSelect(id: String) {
    _isMultiSelectMode.value = true
    _selectedIds.value = setOf(id)
}

fun toggleSelected(id: String) {
    val next = _selectedIds.value.toMutableSet()
    if (!next.add(id)) next.remove(id)
    _selectedIds.value = next
    // Tapping the last selection off does not auto-exit; "Cancel" exits.
}

fun exitMultiSelect() {
    _isMultiSelectMode.value = false
    _selectedIds.value = emptySet()
}

// ── Soft delete + undo ──────────────────────────────────────────────────
/**
 * One-shot undo event for the snackbar. Carries the label to show and the ids
 * to restore. Consumed by the composable after it shows the snackbar.
 */
data class UndoEvent(val message: String, val ids: List<String>)

private val _undoEvent = MutableStateFlow<UndoEvent?>(null)
val undoEvent: StateFlow<UndoEvent?> = _undoEvent.asStateFlow()
fun consumeUndoEvent() { _undoEvent.value = null }

/** Soft-delete one entry and raise the "[name] moved to trash" undo event. */
fun softDelete(entry: VaultEntry) {
    viewModelScope.launch {
        runCatching { vault.deleteEntry(entry.id) }
        _undoEvent.value = UndoEvent("${entry.title} moved to trash", listOf(entry.id))
    }
}

/** Batch soft-delete the current selection, exit mode, raise "[N] entries…". */
fun batchSoftDelete() {
    val ids = _selectedIds.value.toList()
    if (ids.isEmpty()) return
    viewModelScope.launch {
        ids.forEach { id -> runCatching { vault.deleteEntry(id) } }
        exitMultiSelect()
        _undoEvent.value = UndoEvent("${ids.size} entries moved to trash", ids)
    }
}

/** UNDO action: restore every soft-deleted id from the snackbar event. */
fun restoreEntries(ids: List<String>) {
    viewModelScope.launch { ids.forEach { id -> runCatching { vault.restoreEntry(id) } } }
}

// ── Context-menu copy helpers (reuse existing copyPassword pattern) ──────
private fun copyText(value: String?) {
    val v = value?.takeIf { it.isNotEmpty() } ?: return
    val cm = appContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    cm.setPrimaryClip(ClipData.newPlainText("peach", v))
}

fun copyUsername(entry: VaultEntry) = copyText(entry.username ?: entry.email)

/** Copy the LIVE TOTP code, never the stored seed (mirrors EntryDetailViewModel). */
fun copyTotp(entry: VaultEntry) {
    val seed = entry.totp ?: return
    copyText(TOTPGenerator.generateCode(seed))
}

Note: copyPassword(entry) already exists on the VM (used by swipe-copy) — the context menu reuses it directly.


3. VaultListScreen — composable wiring

3a. New imports

import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.material3.Snackbar
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.foundation.layout.Box
import androidx.compose.ui.platform.LocalView

(Box, LocalContext, getValue, remember are already imported.)

3b. Collect new state + set up snackbar/long-press plumbing

Anchor — top of VaultListScreen body, the existing collectAsState block:

    val entries by vm.entries.collectAsState()
    val sort by vm.sort.collectAsState()
    val search by vm.search.collectAsState()
    val total by vm.totalCount.collectAsState()
    val flashId by vm.flashId.collectAsState()

Add immediately after it:

    val isMultiSelect by vm.isMultiSelectMode.collectAsState()
    val selectedIds by vm.selectedIds.collectAsState()
    val undoEvent by vm.undoEvent.collectAsState()
    val snackbarHostState = remember { SnackbarHostState() }
    var menuEntry by remember { mutableStateOf<VaultEntry?>(null) }

    // Drain VM undo events into the snackbar host; UNDO restores the ids.
    LaunchedEffect(undoEvent) {
        val ev = undoEvent ?: return@LaunchedEffect
        vm.consumeUndoEvent()
        val result = snackbarHostState.showSnackbar(
            message = ev.message,
            actionLabel = "UNDO",
            duration = androidx.compose.material3.SnackbarDuration.Short, // ~4s; spec asks 5s
        )
        if (result == SnackbarResult.ActionPerformed) vm.restoreEntries(ev.ids)
    }

5s auto-dismiss: SnackbarDuration.Short is ~4s and .Long ~10s. If exactly 5s is required, omit duration and use a manual delay(5000) race, or accept Short. Recommend Short for platform consistency.

3c. Wrap the screen so the snackbar host overlays, and swap the top bar

Anchor — the existing root of the screen:

    ShellBackground {
        Column(Modifier.fillMaxSize()) {
            TopBar(
                onSettings = { onNavigate(PeachNav.Settings) },
                onAdd = { onNavigate(PeachNav.EntryEdit(null)) },
            )

Replace the ShellBackground { Column(...) { opening and the TopBar(...) call with:

    ShellBackground {
        Box(Modifier.fillMaxSize()) {
        Column(Modifier.fillMaxSize()) {
            if (isMultiSelect) {
                MultiSelectTopBar(
                    count = selectedIds.size,
                    onDelete = { vm.batchSoftDelete() },
                    onCancel = { vm.exitMultiSelect() },
                )
            } else {
                TopBar(
                    onSettings = { onNavigate(PeachNav.Settings) },
                    onAdd = { onNavigate(PeachNav.EntryEdit(null)) },
                )
            }

Then anchor — the closing of the screen:

                item {
                    NewEntryRow(onClick = { onNavigate(PeachNav.EntryEdit(null)) })
                    Spacer(Modifier.navigationBarsPadding())
                }
            }
        }
    }
}

Replace with (adds the snackbar host + closes the new Box):

                item {
                    NewEntryRow(onClick = { onNavigate(PeachNav.EntryEdit(null)) })
                    Spacer(Modifier.navigationBarsPadding())
                }
            }
        }
        SnackbarHost(
            hostState = snackbarHostState,
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .navigationBarsPadding(),
        ) { data ->
            // Peach-styled snackbar: glass panel, accent UNDO label.
            Snackbar(
                containerColor = PeachColors.SurfaceElevated,
                contentColor = PeachColors.T0,
                actionContentColor = LocalPeachAccent.current,
                snackbarData = data,
            )
        }
        } // Box
    }

    menuEntry?.let { e ->
        ContextMenuSheet(
            entry = e,
            onCopyPassword = { vm.copyPassword(e); PeachHaptics.onCopy(view) },
            onCopyUsername = { vm.copyUsername(e); PeachHaptics.onCopy(view) },
            onCopyTotp = { vm.copyTotp(e); PeachHaptics.onCopy(view) },
            onEdit = { onNavigate(PeachNav.EntryEdit(e.id)) },
            onMoveToTrash = { vm.softDelete(e) },
            onDismiss = { menuEntry = null },
        )
    }
}

For PeachHaptics.onCopy(view) add val view = LocalView.current near the top of VaultListScreen (and import com.peachpasswords.haptics.PeachHaptics, androidx.compose.ui.platform.LocalView). LocalPeachAccent and PeachColors are already imported.

3d. EntryRow — long-press + multi-select hooks

The items(...) call needs the new params threaded through. Anchor:

                items(entries, key = { it.id }) { entry ->
                    EntryRow(
                        entry = entry,
                        flashing = flashId == entry.id,
                        canSwipeCopy = vm.canSwipeCopy(entry),
                        onTap = { onNavigate(PeachNav.EntryDetail(entry.id)) },
                        onSwipeCopy = { vm.copyPassword(entry) },
                    )
                }

Replace with:

                items(entries, key = { it.id }) { entry ->
                    EntryRow(
                        entry = entry,
                        flashing = flashId == entry.id,
                        canSwipeCopy = vm.canSwipeCopy(entry) && !isMultiSelect,
                        multiSelect = isMultiSelect,
                        selected = entry.id in selectedIds,
                        onTap = {
                            if (isMultiSelect) vm.toggleSelected(entry.id)
                            else onNavigate(PeachNav.EntryDetail(entry.id))
                        },
                        onLongPress = {
                            if (isMultiSelect) vm.toggleSelected(entry.id)
                            else menuEntry = entry
                        },
                        onSwipeCopy = { vm.copyPassword(entry) },
                    )
                }

Spec offers two long-press behaviours: (a) open context menu, (b) enter multi-select. This wiring uses (a) — long-press opens the menu, and the menu's "Move to trash" handles single delete. To make long-press enter multi-select instead, change onLongPress to { vm.enterMultiSelect(entry.id) } and add a "Select" button to the top bar that opens the menu, OR keep both: short menu has a "Select" row. Recommend (a) as primary; enterMultiSelect is provided on the VM if you want long-press → multi-select. Pick one and keep it consistent.

3e. EntryRow signature + body changes

Anchor — the existing EntryRow signature and the pointerInput/clickable block:

@Composable
private fun EntryRow(
    entry: VaultEntry,
    flashing: Boolean,
    canSwipeCopy: Boolean,
    onTap: () -> Unit,
    onSwipeCopy: () -> Unit,
) {

Replace the signature with:

@Composable
private fun EntryRow(
    entry: VaultEntry,
    flashing: Boolean,
    canSwipeCopy: Boolean,
    multiSelect: Boolean,
    selected: Boolean,
    onTap: () -> Unit,
    onLongPress: () -> Unit,
    onSwipeCopy: () -> Unit,
) {

Inside EntryRow, the existing swipe pointerInput block stays. Add a second pointerInput for the 500ms long-press with haptic. Anchor — the existing .clickable(...) line on the row Modifier:

            .clickable(interactionSource = interaction, indication = null, onClick = onTap)
            .padding(horizontal = 16.dp, vertical = 9.dp),

Insert a long-press detector before the .clickable(...) line:

            .pointerInput(entry.id, multiSelect) {
                detectTapGestures(
                    onLongPress = {
                        PeachHaptics.onLongPress(context)
                        onLongPress()
                    },
                )
            }
            .clickable(interactionSource = interaction, indication = null, onClick = onTap)
            .padding(horizontal = 16.dp, vertical = 9.dp),

detectTapGestures(onLongPress=...) uses Compose's default long-press timeout (~400–500ms via viewConfiguration.longPressTimeoutMillis), satisfying the 500ms spec without a manual timer. Imports to add to VaultListScreen: import androidx.compose.foundation.gestures.detectTapGestures. context and PeachHaptics are already in scope inside EntryRow (context = LocalContext.current, PeachHaptics already imported).

Finally, render the checkbox at the row's leading edge in multi-select. Anchor — the first child of the row Row { ... }:

        FaviconInitials(source = entry.url ?: entry.title, size = 26.dp)

Replace with:

        if (multiSelect) {
            MultiSelectCheckbox(checked = selected)
        }
        FaviconInitials(source = entry.url ?: entry.title, size = 26.dp)

(The row Arrangement.spacedBy(10.dp) already spaces the checkbox from the favicon.)


4. Assumptions / risks