TotpInlineEdit.kt

12.1 KB · raw

1package com.peachpasswords.ui.vault23/*4 * E6 — TOTP double-tap to edit the 2FA secret, inline in EntryDetailScreen.5 *6 * Self-contained drop-in composable. D6 / D7 / E6 all touch EntryDetailScreen.kt,7 * so this stays isolated with merge anchors documented in INTEGRATION.md.8 *9 * Provides:10 *   - TotpBandEditable : a TOTP band that double-taps (or taps a 14dp pencil) into11 *                        an inline 2FA-secret editor — masked BasicTextField with an12 *                        eye toggle and a ✓ save / ✗ cancel row (mirrors the D613 *                        inline-edit visual pattern). On save it calls back with the14 *                        new secret; live regeneration happens automatically because15 *                        the band reads the field flowing in from the VM/entry.16 *17 * It deliberately does NOT reuse the private FieldShell / CopyButton helpers in18 * EntryDetailScreen.kt by name in a way that would force them to change visibility —19 * the band has its own accent-tinted chrome (matching the existing TotpBand), and a20 * local copy button. The only EntryDetailScreen helper it depends on at merge time21 * is the existing `CopyButton`, which already lives in the same file; if the22 * orchestrator instead drops this into a separate file, make `CopyButton` `internal`23 * (see INTEGRATION.md). All private helpers here are E6-prefixed to avoid colliding24 * with D6's identically-shaped UnderlinedField / SaveCancelRow.25 */2627import androidx.compose.animation.core.RepeatMode28import androidx.compose.animation.core.animateFloat29import androidx.compose.animation.core.infiniteRepeatable30import androidx.compose.animation.core.rememberInfiniteTransition31import androidx.compose.animation.core.tween32import androidx.compose.foundation.background33import androidx.compose.foundation.border34import androidx.compose.foundation.clickable35import androidx.compose.foundation.gestures.detectTapGestures36import androidx.compose.foundation.layout.Arrangement37import androidx.compose.foundation.layout.Box38import androidx.compose.foundation.layout.Column39import androidx.compose.foundation.layout.Row40import androidx.compose.foundation.layout.Spacer41import androidx.compose.foundation.layout.fillMaxWidth42import androidx.compose.foundation.layout.height43import androidx.compose.foundation.layout.padding44import androidx.compose.foundation.layout.size45import androidx.compose.foundation.layout.width46import androidx.compose.foundation.shape.RoundedCornerShape47import androidx.compose.foundation.text.BasicTextField48import androidx.compose.material.icons.Icons49import androidx.compose.material.icons.outlined.Edit50import androidx.compose.material3.Icon51import androidx.compose.material3.Text52import androidx.compose.runtime.Composable53import androidx.compose.runtime.getValue54import androidx.compose.runtime.mutableStateOf55import androidx.compose.runtime.produceState56import androidx.compose.runtime.remember57import androidx.compose.runtime.setValue58import androidx.compose.ui.Alignment59import androidx.compose.ui.Modifier60import androidx.compose.ui.draw.clip61import androidx.compose.ui.draw.drawBehind62import androidx.compose.ui.geometry.Offset63import androidx.compose.ui.graphics.SolidColor64import androidx.compose.ui.graphics.graphicsLayer65import androidx.compose.ui.input.pointer.pointerInput66import androidx.compose.ui.text.input.PasswordVisualTransformation67import androidx.compose.ui.text.input.VisualTransformation68import androidx.compose.ui.unit.dp69import androidx.compose.ui.unit.em70import com.peachpasswords.ui.components.TOTPRing71import com.peachpasswords.ui.theme.LocalPeachAccent72import com.peachpasswords.ui.theme.LocalReduceMotion73import com.peachpasswords.ui.theme.PeachColors74import com.peachpasswords.ui.theme.PeachType75import com.peachpasswords.vault.TOTPGenerator7677/**78 * Accent-tinted TOTP band with double-tap-to-edit of the underlying 2FA secret.79 *80 * View mode is visually identical to the existing private `TotpBand`: large code,81 * mono countdown, sweep ring, copy button. A 14dp pencil sits beside the code, and82 * a double-tap anywhere on the code/band enters edit mode.83 *84 * Edit mode shows a masked [BasicTextField] (eye toggle to reveal) seeded with the85 * raw `totp` field (a base32 secret or an `otpauth://` URI), labelled "2FA SECRET",86 * over a ✓ save / ✗ cancel row. The draft is validated with87 * [TOTPGenerator.generateCode]; an empty / unparseable secret shows88 * "Invalid 2FA secret" in breach color and blocks save.89 *90 * On a valid save [onSaveSecret] is invoked with the trimmed new secret — the caller91 * persists via `vm.updateEntry(entry.copy(totp = newValue))`. Because [totpField]92 * flows back in from the entry StateFlow, the band regenerates live with no extra93 * wiring.94 *95 * @param totpField the current raw `totp` value (base32 secret or otpauth URI).96 * @param copied    copy-latch for this entry's TOTP (drives the copy button feedback).97 * @param onCopy    copies the live code (NOT the secret) — wire to `vm::copyTotp`.98 * @param onSaveSecret called with the trimmed, validated new secret on ✓ save.99 */100@Composable101fun TotpBandEditable(102    totpField: String,103    copied: Boolean,104    onCopy: () -> Unit,105    onSaveSecret: (String) -> Unit,106) {107    val accent = LocalPeachAccent.current108    val reduceMotion = LocalReduceMotion.current109110    var editing by remember(totpField) { mutableStateOf(false) }111112    Box(113        Modifier114            .fillMaxWidth()115            .padding(vertical = 10.dp)116            .clip(RoundedCornerShape(8.dp))117            .background(accent.copy(alpha = 0.08f))118            .border(1.dp, accent.copy(alpha = 0.20f), RoundedCornerShape(8.dp))119            .padding(horizontal = 14.dp, vertical = 10.dp),120    ) {121        if (!editing) {122            TotpView(123                totpField = totpField,124                accent = accent,125                reduceMotion = reduceMotion,126                copied = copied,127                onCopy = onCopy,128                onEnterEdit = { editing = true },129            )130        } else {131            TotpSecretEditor(132                initial = totpField,133                onSave = { newSecret -> onSaveSecret(newSecret); editing = false },134                onCancel = { editing = false },135            )136        }137    }138}139140/** Read-only band content: code, countdown, ring, pencil, copy — plus double-tap-to-edit. */141@Composable142private fun TotpView(143    totpField: String,144    accent: androidx.compose.ui.graphics.Color,145    reduceMotion: Boolean,146    copied: Boolean,147    onCopy: () -> Unit,148    onEnterEdit: () -> Unit,149) {150    val code by produceState(TOTPGenerator.generateCode(totpField) ?: "------", totpField) {151        while (true) {152            value = TOTPGenerator.generateCode(totpField) ?: "------"153            kotlinx.coroutines.delay(1000)154        }155    }156    val remaining by produceState(TOTPGenerator.remainingSeconds()) {157        while (true) { value = TOTPGenerator.remainingSeconds(); kotlinx.coroutines.delay(500) }158    }159    val isHot = remaining <= 5160    val pulse = rememberInfiniteTransition(label = "totp-pulse")161    val pulseAlpha by pulse.animateFloat(162        initialValue = 0.55f, targetValue = 1f,163        animationSpec = infiniteRepeatable(tween(600), RepeatMode.Reverse), label = "totp-pulse-alpha",164    )165    val codeAlpha = if (isHot && !reduceMotion) pulseAlpha else 1f166167    Row(verticalAlignment = Alignment.CenterVertically) {168        Column(169            Modifier170                .weight(1f)171                // Double-tap the code area to edit the 2FA secret (E6).172                .pointerInput(Unit) { detectTapGestures(onDoubleTap = { onEnterEdit() }) },173        ) {174            Row(verticalAlignment = Alignment.CenterVertically) {175                Text(176                    "ONE-TIME CODE",177                    color = accent.copy(alpha = 0.70f),178                    style = PeachType.labelMono.copy(letterSpacing = 0.08.em),179                )180                Spacer(Modifier.width(6.dp))181                Icon(182                    Icons.Outlined.Edit,183                    contentDescription = "edit 2FA secret",184                    tint = PeachColors.T2,185                    modifier = Modifier186                        .size(14.dp)187                        .clip(RoundedCornerShape(4.dp))188                        .clickable(onClick = onEnterEdit),189                )190            }191            val spaced = if (code.length == 6) "${code.substring(0, 3)} ${code.substring(3)}" else code192            Text(193                spaced,194                color = if (isHot) PeachColors.Breach else accent,195                style = PeachType.totpCode,196                modifier = Modifier.graphicsLayer { alpha = codeAlpha },197            )198        }199        Text("${remaining}s", color = PeachColors.T2, style = PeachType.totpCountdown)200        Spacer(Modifier.width(12.dp))201        TOTPRing(size = 28.dp)202        Spacer(Modifier.width(8.dp))203        CopyButton(copied, onCopy)204    }205}206207/** Inline 2FA-secret editor: masked underlined field + eye toggle + ✓/✗, with validation. */208@Composable209private fun TotpSecretEditor(210    initial: String,211    onSave: (String) -> Unit,212    onCancel: () -> Unit,213) {214    val accent = LocalPeachAccent.current215    var draft by remember { mutableStateOf(initial) }216    var show by remember { mutableStateOf(false) }217    var showError by remember { mutableStateOf(false) }218219    val trimmed = draft.trim()220    val valid = TOTPGenerator.generateCode(trimmed) != null221222    Column(Modifier.fillMaxWidth()) {223        Text(224            "2FA SECRET",225            color = accent.copy(alpha = 0.70f),226            style = PeachType.labelMono.copy(letterSpacing = 0.08.em),227        )228        Spacer(Modifier.height(8.dp))229        Row(verticalAlignment = Alignment.CenterVertically) {230            E6UnderlinedField(231                draft = draft,232                onDraftChange = { draft = it; showError = false },233                transformation = if (show) VisualTransformation.None else PasswordVisualTransformation(),234                modifier = Modifier.weight(1f),235            )236            Text(237                if (show) "hide" else "show", color = accent, style = PeachType.labelMono,238                modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable { show = !show }.padding(6.dp),239            )240        }241        if (showError) {242            Spacer(Modifier.height(6.dp))243            Text("Invalid 2FA secret", color = PeachColors.Breach, style = PeachType.labelMono)244        }245        Spacer(Modifier.height(8.dp))246        E6SaveCancelRow(247            onSave = {248                if (valid) onSave(trimmed) else showError = true249            },250            onCancel = { onCancel() },251        )252    }253}254255/** BasicTextField with an accent underline (mirrors D6's inline-edit field). */256@Composable257private fun E6UnderlinedField(258    draft: String,259    onDraftChange: (String) -> Unit,260    transformation: VisualTransformation = VisualTransformation.None,261    modifier: Modifier = Modifier,262) {263    val accent = LocalPeachAccent.current264    BasicTextField(265        value = draft,266        onValueChange = onDraftChange,267        singleLine = true,268        textStyle = PeachType.bodyMono.copy(color = PeachColors.T0),269        cursorBrush = SolidColor(accent),270        visualTransformation = transformation,271        modifier = modifier272            .padding(bottom = 4.dp)273            .drawBehind {274                drawLine(275                    color = accent,276                    start = Offset(0f, size.height),277                    end = Offset(size.width, size.height),278                    strokeWidth = 1.dp.toPx(),279                )280            },281    )282}283284@Composable285private fun E6SaveCancelRow(onSave: () -> Unit, onCancel: () -> Unit) {286    val accent = LocalPeachAccent.current287    Row(horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically) {288        Text(289            "✓ save", color = accent, style = PeachType.labelMono,290            modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onSave).padding(vertical = 4.dp),291        )292        Text(293            "✗", color = PeachColors.T2, style = PeachType.labelMono,294            modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onCancel).padding(horizontal = 6.dp, vertical = 4.dp),295        )296    }297}