EntryDetailScreen.kt

16.5 KB · raw

1package com.peachpasswords.ui.vault23import android.view.WindowManager4import androidx.compose.animation.core.LinearEasing5import androidx.compose.animation.core.RepeatMode6import androidx.compose.animation.core.animateFloat7import androidx.compose.animation.core.animateFloatAsState8import androidx.compose.animation.core.infiniteRepeatable9import androidx.compose.animation.core.rememberInfiniteTransition10import androidx.compose.animation.core.tween11import androidx.compose.foundation.background12import androidx.compose.foundation.border13import androidx.compose.foundation.clickable14import androidx.compose.foundation.layout.Arrangement15import androidx.compose.foundation.layout.Box16import androidx.compose.foundation.layout.Column17import androidx.compose.foundation.layout.Row18import androidx.compose.foundation.layout.Spacer19import androidx.compose.foundation.layout.fillMaxSize20import androidx.compose.foundation.layout.fillMaxWidth21import androidx.compose.foundation.layout.height22import androidx.compose.foundation.layout.offset23import androidx.compose.foundation.layout.padding24import androidx.compose.foundation.layout.size25import androidx.compose.foundation.layout.statusBarsPadding26import androidx.compose.foundation.layout.width27import androidx.compose.foundation.rememberScrollState28import androidx.compose.foundation.shape.CircleShape29import androidx.compose.foundation.shape.RoundedCornerShape30import androidx.compose.material.icons.rounded.Check31import androidx.compose.material.icons.rounded.ContentCopy32import androidx.compose.foundation.verticalScroll33import androidx.compose.material.icons.Icons34import androidx.compose.material.icons.automirrored.rounded.ArrowBack35import androidx.compose.material.icons.outlined.DeleteOutline36import androidx.compose.material3.Icon37import androidx.compose.material3.Text38import androidx.compose.runtime.Composable39import androidx.compose.runtime.DisposableEffect40import androidx.compose.runtime.getValue41import androidx.compose.runtime.mutableStateOf42import androidx.compose.runtime.produceState43import androidx.compose.runtime.remember44import androidx.compose.runtime.setValue45import androidx.compose.ui.Alignment46import androidx.compose.ui.Modifier47import androidx.compose.ui.draw.clip48import androidx.compose.ui.draw.drawBehind49import androidx.compose.ui.geometry.Offset50import androidx.compose.ui.geometry.Size51import androidx.compose.ui.graphics.Brush52import androidx.compose.ui.graphics.Color53import androidx.compose.ui.graphics.graphicsLayer54import androidx.compose.ui.platform.LocalContext55import androidx.compose.ui.text.TextStyle56import androidx.compose.ui.unit.dp57import androidx.compose.ui.unit.em58import androidx.compose.ui.unit.sp59import androidx.compose.runtime.collectAsState60import androidx.fragment.app.FragmentActivity61import androidx.hilt.navigation.compose.hiltViewModel62import com.peachpasswords.ui.PeachNav63import com.peachpasswords.ui.components.CharEnterText64import com.peachpasswords.ui.components.FaviconInitials65import com.peachpasswords.ui.components.TOTPRing66import com.peachpasswords.ui.lock.Biometrics67import com.peachpasswords.ui.theme.LocalPeachAccent68import com.peachpasswords.ui.theme.LocalReduceMotion69import com.peachpasswords.ui.theme.PeachColors70import com.peachpasswords.ui.theme.PeachType71import com.peachpasswords.ui.theme.ShellBackground72import com.peachpasswords.vault.TOTPGenerator73import com.peachpasswords.vault.hasTOTP7475@Composable76fun EntryDetailScreen(77    id: String,78    onNavigate: (PeachNav) -> Unit,79    onBack: () -> Unit,80    vm: EntryDetailViewModel = hiltViewModel(),81) {82    val entry by vm.entry.collectAsState()83    val revealed by vm.revealed.collectAsState()84    val copiedField by vm.copiedField.collectAsState()85    val context = LocalContext.current86    val accent = LocalPeachAccent.current87    var confirmingDelete by remember { mutableStateOf(false) }8889    // FLAG_SECURE only while this screen is shown — blocks screenshots of secrets.90    DisposableEffect(Unit) {91        val window = (context as? FragmentActivity)?.window92        window?.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)93        onDispose { window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) }94    }9596    val e = entry97    ShellBackground {98        Column(Modifier.fillMaxSize().statusBarsPadding()) {99            // Header: back · favicon+domain (or delete confirm) · trash100            Row(101                Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 8.dp),102                verticalAlignment = Alignment.CenterVertically,103            ) {104                Icon(105                    Icons.AutoMirrored.Rounded.ArrowBack, contentDescription = "back", tint = PeachColors.T0,106                    modifier = Modifier.size(40.dp).clip(CircleShape).clickable(onClick = onBack).padding(8.dp),107                )108                Box(Modifier.weight(1f), contentAlignment = Alignment.Center) {109                    when {110                        e == null -> {}111                        confirmingDelete -> Text(112                            "delete “${e.title}”?",113                            color = PeachColors.Breach,114                            style = PeachType.labelMono.copy(letterSpacing = 0.08.em),115                        )116                        else -> Row(117                            verticalAlignment = Alignment.CenterVertically,118                            horizontalArrangement = Arrangement.spacedBy(8.dp),119                        ) {120                            FaviconInitials(source = e.url ?: e.title, size = 16.dp)121                            val domain = remember(e.url, e.title) { e.displayDomain() }122                            if (domain.isNotEmpty()) {123                                Text(domain, color = PeachColors.T2, style = TextStyle(fontFamily = PeachType.Mono, fontSize = 9.sp))124                            }125                        }126                    }127                }128                if (e != null) {129                    Icon(130                        Icons.Outlined.DeleteOutline, contentDescription = "delete",131                        tint = if (confirmingDelete) PeachColors.Breach else PeachColors.T1,132                        modifier = Modifier.size(40.dp).clip(CircleShape)133                            .clickable { if (confirmingDelete) vm.delete(onDone = onBack) else confirmingDelete = true }134                            .padding(8.dp),135                    )136                }137            }138139            if (e == null) {140                Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {141                    Text("entry not found", color = PeachColors.T1, style = PeachType.bodyMono)142                }143                return@Column144            }145146            Column(147                Modifier.fillMaxSize().verticalScroll(rememberScrollState())148                    .padding(horizontal = 24.dp),149            ) {150                // Hero — ghost PeachScript watermark behind the entry name.151                Box(Modifier.fillMaxWidth()) {152                    Text(153                        text = e.title.firstOrNull()?.uppercase() ?: "P",154                        style = TextStyle(fontFamily = PeachType.Script, fontSize = 140.sp),155                        color = PeachColors.T0.copy(alpha = 0.03f),156                        modifier = Modifier.align(Alignment.TopCenter).offset(y = (-16).dp),157                    )158                    Column(Modifier.fillMaxWidth().padding(top = 18.dp)) {159                        CharEnterText(160                            text = e.title,161                            style = PeachType.entryNameHero.copy(color = PeachColors.T0),162                        )163                        Spacer(Modifier.height(8.dp))164                        Text(165                            text = "edit",166                            color = accent,167                            style = PeachType.labelMono,168                            modifier = Modifier.clip(RoundedCornerShape(6.dp))169                                .clickable { onNavigate(PeachNav.EntryEdit(e.id)) }170                                .padding(vertical = 4.dp),171                        )172                    }173                }174                Spacer(Modifier.height(20.dp))175176                e.username?.takeIf { it.isNotBlank() }?.let {177                    FieldRow("username", it, copiedField == "username") { vm.copy("username", it) }178                }179                e.email?.takeIf { it.isNotBlank() }?.let {180                    FieldRow("email", it, copiedField == "email") { vm.copy("email", it) }181                }182                e.password?.takeIf { it.isNotBlank() }?.let { pw ->183                    PasswordRow(184                        value = pw,185                        revealed = revealed,186                        copied = copiedField == "password",187                        onReveal = {188                            if (revealed) vm.mask()189                            else {190                                val activity = context as? FragmentActivity191                                if (activity != null && Biometrics.isAvailable(context)) {192                                    Biometrics.authenticate(activity, "Unlock Peach", e.title, onSuccess = vm::reveal)193                                } else vm.reveal()194                            }195                        },196                        onCopy = { vm.copy("password", pw) },197                    )198                }199                if (e.hasTOTP()) {200                    Spacer(Modifier.height(4.dp))201                    TotpBand(totpField = e.totp!!, copied = copiedField == "totp", onCopy = vm::copyTotp)202                }203                e.notes?.takeIf { it.isNotBlank() }?.let {204                    FieldRow("notes", it, copiedField == "notes", mono = false) { vm.copy("notes", it) }205                }206207                Spacer(Modifier.height(48.dp))208            }209        }210    }211}212213@Composable214private fun FieldRow(215    label: String,216    value: String,217    copied: Boolean,218    mono: Boolean = true,219    onCopy: () -> Unit,220) {221    FieldShell(label) {222        Text(223            value,224            color = PeachColors.T0,225            style = if (mono) PeachType.bodyMono else PeachType.body,226            modifier = Modifier.weight(1f),227        )228        CopyButton(copied, onCopy)229    }230}231232@Composable233private fun PasswordRow(234    value: String,235    revealed: Boolean,236    copied: Boolean,237    onReveal: () -> Unit,238    onCopy: () -> Unit,239) {240    val accent = LocalPeachAccent.current241    FieldShell("password") {242        Text(243            text = if (revealed) value else "•".repeat(value.length.coerceIn(8, 16)),244            color = PeachColors.T0,245            style = PeachType.bodyMono,246            modifier = Modifier.weight(1f),247        )248        Text(249            if (revealed) "hide" else "show", color = accent, style = PeachType.labelMono,250            modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onReveal).padding(8.dp),251        )252        CopyButton(copied, onCopy)253    }254}255256/** A field row: uppercase mono label over a value/action row, with a t3 hairline beneath (spec §5.4). */257@Composable258private fun FieldShell(259    label: String,260    content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit,261) {262    Column(263        Modifier.fillMaxWidth().padding(vertical = 10.dp).drawBehind {264            drawRect(265                color = PeachColors.T3,266                topLeft = Offset(0f, size.height - 1.dp.toPx()),267                size = Size(size.width, 1.dp.toPx()),268            )269        },270    ) {271        Text(label.uppercase(), color = PeachColors.T2, style = PeachType.labelMono.copy(letterSpacing = 0.08.em))272        Spacer(Modifier.height(6.dp))273        Row(verticalAlignment = Alignment.CenterVertically, content = content)274    }275}276277/** Accent-tinted TOTP band (spec §5.4): large Cormorant code, mono countdown, sweep ring. */278@Composable279private fun TotpBand(totpField: String, copied: Boolean, onCopy: () -> Unit) {280    val accent = LocalPeachAccent.current281    val reduceMotion = LocalReduceMotion.current282    val code by produceState(TOTPGenerator.generateCode(totpField) ?: "------") {283        while (true) {284            value = TOTPGenerator.generateCode(totpField) ?: "------"285            kotlinx.coroutines.delay(1000)286        }287    }288    val remaining by produceState(TOTPGenerator.remainingSeconds()) {289        while (true) { value = TOTPGenerator.remainingSeconds(); kotlinx.coroutines.delay(500) }290    }291    val isHot = remaining <= 5292    // Gentle pulse for the final 5s; the transition always runs but only applies when hot.293    val pulse = rememberInfiniteTransition(label = "totp-pulse")294    val pulseAlpha by pulse.animateFloat(295        initialValue = 0.55f, targetValue = 1f,296        animationSpec = infiniteRepeatable(tween(600), RepeatMode.Reverse), label = "totp-pulse-alpha",297    )298    val codeAlpha = if (isHot && !reduceMotion) pulseAlpha else 1f299300    Box(301        Modifier302            .fillMaxWidth()303            .padding(vertical = 10.dp)304            .clip(RoundedCornerShape(8.dp))305            .background(accent.copy(alpha = 0.08f))306            .border(1.dp, accent.copy(alpha = 0.20f), RoundedCornerShape(8.dp))307            .padding(horizontal = 14.dp, vertical = 10.dp),308    ) {309        Row(verticalAlignment = Alignment.CenterVertically) {310            Column(Modifier.weight(1f)) {311                Text(312                    "ONE-TIME CODE",313                    color = accent.copy(alpha = 0.70f),314                    style = PeachType.labelMono.copy(letterSpacing = 0.08.em),315                )316                val spaced = if (code.length == 6) "${code.substring(0, 3)} ${code.substring(3)}" else code317                Text(318                    spaced,319                    color = if (isHot) PeachColors.Breach else accent,320                    style = PeachType.totpCode,321                    modifier = Modifier.graphicsLayer { alpha = codeAlpha },322                )323            }324            Text("${remaining}s", color = PeachColors.T2, style = PeachType.totpCountdown)325            Spacer(Modifier.width(12.dp))326            TOTPRing(size = 28.dp)327            Spacer(Modifier.width(8.dp))328            CopyButton(copied, onCopy)329        }330    }331}332333/**334 * Copy button with the two-effect copy feedback (spec §4.4): a diagonal sheen335 * sweeps once over ~600ms and an accent drain bar fills 0→100% over 1.4s. Both336 * collapse instantly when the copied latch clears, and are skipped under337 * reduce-motion.338 */339@Composable340private fun CopyButton(copied: Boolean, onCopy: () -> Unit) {341    val accent = LocalPeachAccent.current342    val reduceMotion = LocalReduceMotion.current343    val animate = copied && !reduceMotion344    val drain by animateFloatAsState(345        targetValue = if (copied) 1f else 0f,346        animationSpec = if (animate) tween(1400, easing = LinearEasing) else tween(0),347        label = "copy-drain",348    )349    val sheen by animateFloatAsState(350        targetValue = if (copied) 1f else 0f,351        animationSpec = if (animate) tween(600, easing = LinearEasing) else tween(0),352        label = "copy-sheen",353    )354    Box(355        Modifier356            .size(36.dp)357            .clip(RoundedCornerShape(6.dp))358            .background(PeachColors.S2)359            .clickable(onClick = onCopy)360            .drawBehind {361                if (animate && sheen < 1f) {362                    val sweepX = (sheen * 2f - 0.5f) * size.width363                    val band = size.width * 0.5f364                    drawRect(365                        brush = Brush.linearGradient(366                            colors = listOf(Color.Transparent, accent.copy(alpha = 0.35f), Color.Transparent),367                            start = Offset(sweepX - band, 0f),368                            end = Offset(sweepX + band, size.height),369                        ),370                    )371                }372                if (drain > 0f) {373                    val h = 2.dp.toPx()374                    drawRect(375                        color = accent,376                        topLeft = Offset(0f, size.height - h),377                        size = Size(size.width * drain, h),378                    )379                }380            },381        contentAlignment = Alignment.Center,382    ) {383        Icon(384            if (copied) Icons.Rounded.Check else Icons.Rounded.ContentCopy,385            contentDescription = "copy",386            tint = if (copied) accent else PeachColors.T1,387            modifier = Modifier.size(15.dp),388        )389    }390}391392private fun com.peachpasswords.vault.VaultEntry.displayDomain(): String {393    val raw = url394    if (!raw.isNullOrBlank()) {395        val cleaned = raw.replace(Regex("^https?://"), "").removePrefix("www.").substringBefore('/')396        if (cleaned.isNotEmpty()) return cleaned397    }398    return ""399}