EntryDetailScreen.kt

17.7 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.hasTOTP74import com.peachpasswords.vault.isBreach7576@Composable77fun EntryDetailScreen(78    id: String,79    onNavigate: (PeachNav) -> Unit,80    onBack: () -> Unit,81    vm: EntryDetailViewModel = hiltViewModel(),82) {83    val entry by vm.entry.collectAsState()84    val revealed by vm.revealed.collectAsState()85    val copiedField by vm.copiedField.collectAsState()86    val context = LocalContext.current87    val accent = LocalPeachAccent.current88    var confirmingDelete by remember { mutableStateOf(false) }8990    // FLAG_SECURE only while this screen is shown — blocks screenshots of secrets.91    DisposableEffect(Unit) {92        val window = (context as? FragmentActivity)?.window93        window?.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)94        onDispose { window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) }95    }9697    val e = entry98    ShellBackground {99        Column(Modifier.fillMaxSize().statusBarsPadding()) {100            // Header: back · favicon+domain (or delete confirm) · trash101            Row(102                Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 8.dp),103                verticalAlignment = Alignment.CenterVertically,104            ) {105                Icon(106                    Icons.AutoMirrored.Rounded.ArrowBack, contentDescription = "back", tint = PeachColors.T0,107                    modifier = Modifier.size(40.dp).clip(CircleShape).clickable(onClick = onBack).padding(8.dp),108                )109                Box(Modifier.weight(1f), contentAlignment = Alignment.Center) {110                    when {111                        e == null -> {}112                        confirmingDelete -> Text(113                            "delete “${e.title}”?",114                            color = PeachColors.Breach,115                            style = PeachType.labelMono.copy(letterSpacing = 0.08.em),116                        )117                        else -> Row(118                            verticalAlignment = Alignment.CenterVertically,119                            horizontalArrangement = Arrangement.spacedBy(8.dp),120                        ) {121                            FaviconInitials(source = e.url ?: e.title, size = 16.dp)122                            val domain = remember(e.url, e.title) { e.displayDomain() }123                            if (domain.isNotEmpty()) {124                                Text(domain, color = PeachColors.T2, style = TextStyle(fontFamily = PeachType.Mono, fontSize = 9.sp))125                            }126                        }127                    }128                }129                if (e != null) {130                    Icon(131                        Icons.Outlined.DeleteOutline, contentDescription = "delete",132                        tint = if (confirmingDelete) PeachColors.Breach else PeachColors.T1,133                        modifier = Modifier.size(40.dp).clip(CircleShape)134                            .clickable { if (confirmingDelete) vm.delete(onDone = onBack) else confirmingDelete = true }135                            .padding(8.dp),136                    )137                }138            }139140            if (e == null) {141                Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {142                    Text("entry not found", color = PeachColors.T1, style = PeachType.bodyMono)143                }144                return@Column145            }146147            // D11 — breach banner strip when this entry's password is known-compromised.148            if (e.isBreach()) {149                Row(150                    Modifier.fillMaxWidth()151                        .background(PeachColors.BreachBg)152                        .padding(horizontal = 16.dp, vertical = 8.dp),153                    verticalAlignment = Alignment.CenterVertically,154                ) {155                    Text("⚠", color = PeachColors.Breach, style = PeachType.bodyMono)156                    Spacer(Modifier.width(10.dp))157                    Text(158                        "Password found in a data breach — change it now",159                        color = PeachColors.Breach, style = PeachType.labelMono,160                        modifier = Modifier.weight(1f),161                    )162                    Text(163                        "Change password",164                        color = accent, style = PeachType.labelMono,165                        modifier = Modifier.clip(RoundedCornerShape(6.dp))166                            .clickable { onNavigate(PeachNav.EntryEdit(e.id)) }167                            .padding(horizontal = 6.dp, vertical = 4.dp),168                    )169                }170            }171172            Column(173                Modifier.fillMaxSize().verticalScroll(rememberScrollState())174                    .padding(horizontal = 24.dp),175            ) {176                // Hero — ghost PeachScript watermark behind the entry name.177                Box(Modifier.fillMaxWidth()) {178                    Text(179                        text = e.title.firstOrNull()?.uppercase() ?: "P",180                        style = TextStyle(fontFamily = PeachType.Script, fontSize = 140.sp),181                        color = PeachColors.T0.copy(alpha = 0.03f),182                        modifier = Modifier.align(Alignment.TopCenter).offset(y = (-16).dp),183                    )184                    Column(Modifier.fillMaxWidth().padding(top = 18.dp)) {185                        CharEnterText(186                            text = e.title,187                            style = PeachType.entryNameHero.copy(color = PeachColors.T0),188                        )189                        Spacer(Modifier.height(8.dp))190                        Text(191                            text = "edit",192                            color = accent,193                            style = PeachType.labelMono,194                            modifier = Modifier.clip(RoundedCornerShape(6.dp))195                                .clickable { onNavigate(PeachNav.EntryEdit(e.id)) }196                                .padding(vertical = 4.dp),197                        )198                    }199                }200                Spacer(Modifier.height(20.dp))201202                e.username?.takeIf { it.isNotBlank() }?.let {203                    FieldRow("username", it, copiedField == "username") { vm.copy("username", it) }204                }205                e.email?.takeIf { it.isNotBlank() }?.let {206                    FieldRow("email", it, copiedField == "email") { vm.copy("email", it) }207                }208                e.password?.takeIf { it.isNotBlank() }?.let { pw ->209                    PasswordRow(210                        value = pw,211                        revealed = revealed,212                        copied = copiedField == "password",213                        onReveal = {214                            if (revealed) vm.mask()215                            else {216                                val activity = context as? FragmentActivity217                                if (activity != null && Biometrics.isAvailable(context)) {218                                    Biometrics.authenticate(activity, "Unlock Peach", e.title, onSuccess = vm::reveal)219                                } else vm.reveal()220                            }221                        },222                        onCopy = { vm.copy("password", pw) },223                    )224                }225                if (e.hasTOTP()) {226                    Spacer(Modifier.height(4.dp))227                    TotpBand(totpField = e.totp!!, copied = copiedField == "totp", onCopy = vm::copyTotp)228                }229                e.notes?.takeIf { it.isNotBlank() }?.let {230                    FieldRow("notes", it, copiedField == "notes", mono = false) { vm.copy("notes", it) }231                }232233                Spacer(Modifier.height(48.dp))234            }235        }236    }237}238239@Composable240private fun FieldRow(241    label: String,242    value: String,243    copied: Boolean,244    mono: Boolean = true,245    onCopy: () -> Unit,246) {247    FieldShell(label) {248        Text(249            value,250            color = PeachColors.T0,251            style = if (mono) PeachType.bodyMono else PeachType.body,252            modifier = Modifier.weight(1f),253        )254        CopyButton(copied, onCopy)255    }256}257258@Composable259private fun PasswordRow(260    value: String,261    revealed: Boolean,262    copied: Boolean,263    onReveal: () -> Unit,264    onCopy: () -> Unit,265) {266    val accent = LocalPeachAccent.current267    FieldShell("password") {268        Text(269            text = if (revealed) value else "•".repeat(value.length.coerceIn(8, 16)),270            color = PeachColors.T0,271            style = PeachType.bodyMono,272            modifier = Modifier.weight(1f),273        )274        Text(275            if (revealed) "hide" else "show", color = accent, style = PeachType.labelMono,276            modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onReveal).padding(8.dp),277        )278        CopyButton(copied, onCopy)279    }280}281282/** A field row: uppercase mono label over a value/action row, with a t3 hairline beneath (spec §5.4). */283@Composable284private fun FieldShell(285    label: String,286    content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit,287) {288    Column(289        Modifier.fillMaxWidth().padding(vertical = 10.dp).drawBehind {290            drawRect(291                color = PeachColors.T3,292                topLeft = Offset(0f, size.height - 1.dp.toPx()),293                size = Size(size.width, 1.dp.toPx()),294            )295        },296    ) {297        Text(label.uppercase(), color = PeachColors.T2, style = PeachType.labelMono.copy(letterSpacing = 0.08.em))298        Spacer(Modifier.height(6.dp))299        Row(verticalAlignment = Alignment.CenterVertically, content = content)300    }301}302303/** Accent-tinted TOTP band (spec §5.4): large Cormorant code, mono countdown, sweep ring. */304@Composable305private fun TotpBand(totpField: String, copied: Boolean, onCopy: () -> Unit) {306    val accent = LocalPeachAccent.current307    val reduceMotion = LocalReduceMotion.current308    val code by produceState(TOTPGenerator.generateCode(totpField) ?: "------") {309        while (true) {310            value = TOTPGenerator.generateCode(totpField) ?: "------"311            kotlinx.coroutines.delay(1000)312        }313    }314    val remaining by produceState(TOTPGenerator.remainingSeconds()) {315        while (true) { value = TOTPGenerator.remainingSeconds(); kotlinx.coroutines.delay(500) }316    }317    val isHot = remaining <= 5318    // Gentle pulse for the final 5s; the transition always runs but only applies when hot.319    val pulse = rememberInfiniteTransition(label = "totp-pulse")320    val pulseAlpha by pulse.animateFloat(321        initialValue = 0.55f, targetValue = 1f,322        animationSpec = infiniteRepeatable(tween(600), RepeatMode.Reverse), label = "totp-pulse-alpha",323    )324    val codeAlpha = if (isHot && !reduceMotion) pulseAlpha else 1f325326    Box(327        Modifier328            .fillMaxWidth()329            .padding(vertical = 10.dp)330            .clip(RoundedCornerShape(8.dp))331            .background(accent.copy(alpha = 0.08f))332            .border(1.dp, accent.copy(alpha = 0.20f), RoundedCornerShape(8.dp))333            .padding(horizontal = 14.dp, vertical = 10.dp),334    ) {335        Row(verticalAlignment = Alignment.CenterVertically) {336            Column(Modifier.weight(1f)) {337                Text(338                    "ONE-TIME CODE",339                    color = accent.copy(alpha = 0.70f),340                    style = PeachType.labelMono.copy(letterSpacing = 0.08.em),341                )342                val spaced = if (code.length == 6) "${code.substring(0, 3)} ${code.substring(3)}" else code343                Text(344                    spaced,345                    color = if (isHot) PeachColors.Breach else accent,346                    style = PeachType.totpCode,347                    modifier = Modifier.graphicsLayer { alpha = codeAlpha },348                )349            }350            Text("${remaining}s", color = PeachColors.T2, style = PeachType.totpCountdown)351            Spacer(Modifier.width(12.dp))352            TOTPRing(size = 28.dp)353            Spacer(Modifier.width(8.dp))354            CopyButton(copied, onCopy)355        }356    }357}358359/**360 * Copy button with the two-effect copy feedback (spec §4.4): a diagonal sheen361 * sweeps once over ~600ms and an accent drain bar fills 0→100% over 1.4s. Both362 * collapse instantly when the copied latch clears, and are skipped under363 * reduce-motion.364 */365@Composable366private fun CopyButton(copied: Boolean, onCopy: () -> Unit) {367    val accent = LocalPeachAccent.current368    val reduceMotion = LocalReduceMotion.current369    val animate = copied && !reduceMotion370    val drain by animateFloatAsState(371        targetValue = if (copied) 1f else 0f,372        animationSpec = if (animate) tween(1400, easing = LinearEasing) else tween(0),373        label = "copy-drain",374    )375    val sheen by animateFloatAsState(376        targetValue = if (copied) 1f else 0f,377        animationSpec = if (animate) tween(600, easing = LinearEasing) else tween(0),378        label = "copy-sheen",379    )380    Box(381        Modifier382            .size(36.dp)383            .clip(RoundedCornerShape(6.dp))384            .background(PeachColors.S2)385            .clickable(onClick = onCopy)386            .drawBehind {387                if (animate && sheen < 1f) {388                    val sweepX = (sheen * 2f - 0.5f) * size.width389                    val band = size.width * 0.5f390                    drawRect(391                        brush = Brush.linearGradient(392                            colors = listOf(Color.Transparent, accent.copy(alpha = 0.35f), Color.Transparent),393                            start = Offset(sweepX - band, 0f),394                            end = Offset(sweepX + band, size.height),395                        ),396                    )397                }398                if (drain > 0f) {399                    val h = 2.dp.toPx()400                    drawRect(401                        color = accent,402                        topLeft = Offset(0f, size.height - h),403                        size = Size(size.width * drain, h),404                    )405                }406            },407        contentAlignment = Alignment.Center,408    ) {409        Icon(410            if (copied) Icons.Rounded.Check else Icons.Rounded.ContentCopy,411            contentDescription = "copy",412            tint = if (copied) accent else PeachColors.T1,413            modifier = Modifier.size(15.dp),414        )415    }416}417418private fun com.peachpasswords.vault.VaultEntry.displayDomain(): String {419    val raw = url420    if (!raw.isNullOrBlank()) {421        val cleaned = raw.replace(Regex("^https?://"), "").removePrefix("www.").substringBefore('/')422        if (cleaned.isNotEmpty()) return cleaned423    }424    return ""425}