EntryDetailScreen.kt

19.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.hasTOTP74import com.peachpasswords.vault.isBreach75import com.peachpasswords.vault.isCard7677@Composable78fun EntryDetailScreen(79    id: String,80    onNavigate: (PeachNav) -> Unit,81    onBack: () -> Unit,82    vm: EntryDetailViewModel = hiltViewModel(),83) {84    val entry by vm.entry.collectAsState()85    val revealed by vm.revealed.collectAsState()86    val cvcRevealed by vm.cvcRevealed.collectAsState()87    var cardRevealed by remember { mutableStateOf(false) }88    val copiedField by vm.copiedField.collectAsState()89    val context = LocalContext.current90    val accent = LocalPeachAccent.current91    var confirmingDelete by remember { mutableStateOf(false) }9293    // FLAG_SECURE only while this screen is shown — blocks screenshots of secrets.94    DisposableEffect(Unit) {95        val window = (context as? FragmentActivity)?.window96        window?.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)97        onDispose { window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) }98    }99100    val e = entry101    ShellBackground {102        Column(Modifier.fillMaxSize().statusBarsPadding()) {103            // Header: back · favicon+domain (or delete confirm) · trash104            Row(105                Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 8.dp),106                verticalAlignment = Alignment.CenterVertically,107            ) {108                Icon(109                    Icons.AutoMirrored.Rounded.ArrowBack, contentDescription = "back", tint = PeachColors.T0,110                    modifier = Modifier.size(40.dp).clip(CircleShape).clickable(onClick = onBack).padding(8.dp),111                )112                Box(Modifier.weight(1f), contentAlignment = Alignment.Center) {113                    when {114                        e == null -> {}115                        confirmingDelete -> Text(116                            "delete “${e.title}”?",117                            color = PeachColors.Breach,118                            style = PeachType.labelMono.copy(letterSpacing = 0.08.em),119                        )120                        else -> Row(121                            verticalAlignment = Alignment.CenterVertically,122                            horizontalArrangement = Arrangement.spacedBy(8.dp),123                        ) {124                            FaviconInitials(source = e.url ?: e.title, size = 16.dp)125                            val domain = remember(e.url, e.title) { e.displayDomain() }126                            if (domain.isNotEmpty()) {127                                Text(domain, color = PeachColors.T2, style = TextStyle(fontFamily = PeachType.Mono, fontSize = 9.sp))128                            }129                        }130                    }131                }132                if (e != null) {133                    Icon(134                        Icons.Outlined.DeleteOutline, contentDescription = "delete",135                        tint = if (confirmingDelete) PeachColors.Breach else PeachColors.T1,136                        modifier = Modifier.size(40.dp).clip(CircleShape)137                            .clickable { if (confirmingDelete) vm.delete(onDone = onBack) else confirmingDelete = true }138                            .padding(8.dp),139                    )140                }141            }142143            if (e == null) {144                Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {145                    Text("entry not found", color = PeachColors.T1, style = PeachType.bodyMono)146                }147                return@Column148            }149150            // D11 — breach banner strip when this entry's password is known-compromised.151            if (e.isBreach()) {152                Row(153                    Modifier.fillMaxWidth()154                        .background(PeachColors.BreachBg)155                        .padding(horizontal = 16.dp, vertical = 8.dp),156                    verticalAlignment = Alignment.CenterVertically,157                ) {158                    Text("⚠", color = PeachColors.Breach, style = PeachType.bodyMono)159                    Spacer(Modifier.width(10.dp))160                    Text(161                        "Password found in a data breach — change it now",162                        color = PeachColors.Breach, style = PeachType.labelMono,163                        modifier = Modifier.weight(1f),164                    )165                    Text(166                        "Change password",167                        color = accent, style = PeachType.labelMono,168                        modifier = Modifier.clip(RoundedCornerShape(6.dp))169                            .clickable { onNavigate(PeachNav.EntryEdit(e.id)) }170                            .padding(horizontal = 6.dp, vertical = 4.dp),171                    )172                }173            }174175            Column(176                Modifier.fillMaxSize().verticalScroll(rememberScrollState())177                    .padding(horizontal = 24.dp),178            ) {179                // Hero — ghost PeachScript watermark behind the entry name.180                Box(Modifier.fillMaxWidth()) {181                    Text(182                        text = e.title.firstOrNull()?.uppercase() ?: "P",183                        style = TextStyle(fontFamily = PeachType.Script, fontSize = 140.sp),184                        color = PeachColors.T0.copy(alpha = 0.03f),185                        modifier = Modifier.align(Alignment.TopCenter).offset(y = (-16).dp),186                    )187                    Column(Modifier.fillMaxWidth().padding(top = 18.dp)) {188                        CharEnterText(189                            text = e.title,190                            style = PeachType.entryNameHero.copy(color = PeachColors.T0),191                        )192                        Spacer(Modifier.height(8.dp))193                        Text(194                            text = "edit",195                            color = accent,196                            style = PeachType.labelMono,197                            modifier = Modifier.clip(RoundedCornerShape(6.dp))198                                .clickable { onNavigate(PeachNav.EntryEdit(e.id)) }199                                .padding(vertical = 4.dp),200                        )201                    }202                }203                Spacer(Modifier.height(20.dp))204205                if (e.isCard()) {206                    CardDetailFields(207                        entry = e,208                        cardRevealed = cardRevealed,209                        cvcRevealed = cvcRevealed,210                        copiedField = copiedField,211                        onToggleCardReveal = { cardRevealed = !cardRevealed },212                        onRevealCvc = {213                            val activity = context as? FragmentActivity214                            if (activity != null && Biometrics.isAvailable(context)) {215                                Biometrics.authenticate(activity, "Unlock Peach", e.title, onSuccess = vm::revealCvc)216                            } else vm.revealCvc()217                        },218                        onMaskCvc = vm::maskCvc,219                        onCopy = vm::copy,220                        copyButton = { copied, onCopy -> CopyButton(copied, onCopy) },221                    )222                } else {223                    e.username?.takeIf { it.isNotBlank() }?.let {224                        FieldRow("username", it, copiedField == "username") { vm.copy("username", it) }225                    }226                    e.email?.takeIf { it.isNotBlank() }?.let {227                        FieldRow("email", it, copiedField == "email") { vm.copy("email", it) }228                    }229                    e.additionalUrls?.takeIf { it.any { u -> u.isNotBlank() } }?.let { urls ->230                        AdditionalUrlRows(231                            urls = urls,232                            copiedField = copiedField,233                            onCopy = { key, value -> vm.copy(key, value) },234                        )235                    }236                    e.password?.takeIf { it.isNotBlank() }?.let { pw ->237                        PasswordRow(238                            value = pw,239                            revealed = revealed,240                            copied = copiedField == "password",241                            onReveal = {242                                if (revealed) vm.mask()243                                else {244                                    val activity = context as? FragmentActivity245                                    if (activity != null && Biometrics.isAvailable(context)) {246                                        Biometrics.authenticate(activity, "Unlock Peach", e.title, onSuccess = vm::reveal)247                                    } else vm.reveal()248                                }249                            },250                            onCopy = { vm.copy("password", pw) },251                        )252                    }253                    if (e.hasTOTP()) {254                        Spacer(Modifier.height(4.dp))255                        TotpBand(totpField = e.totp!!, copied = copiedField == "totp", onCopy = vm::copyTotp)256                    }257                }258                e.notes?.takeIf { it.isNotBlank() }?.let {259                    FieldRow("notes", it, copiedField == "notes", mono = false) { vm.copy("notes", it) }260                }261                e.tags?.takeIf { it.isNotEmpty() }?.let { tags ->262                    DetailTagRow(263                        tags = tags,264                        onEditTags = { onNavigate(PeachNav.EntryEdit(e.id)) },265                    )266                }267268                Spacer(Modifier.height(48.dp))269            }270        }271    }272}273274@Composable275private fun FieldRow(276    label: String,277    value: String,278    copied: Boolean,279    mono: Boolean = true,280    onCopy: () -> Unit,281) {282    FieldShell(label) {283        Text(284            value,285            color = PeachColors.T0,286            style = if (mono) PeachType.bodyMono else PeachType.body,287            modifier = Modifier.weight(1f),288        )289        CopyButton(copied, onCopy)290    }291}292293@Composable294private fun PasswordRow(295    value: String,296    revealed: Boolean,297    copied: Boolean,298    onReveal: () -> Unit,299    onCopy: () -> Unit,300) {301    val accent = LocalPeachAccent.current302    FieldShell("password") {303        Text(304            text = if (revealed) value else "•".repeat(value.length.coerceIn(8, 16)),305            color = PeachColors.T0,306            style = PeachType.bodyMono,307            modifier = Modifier.weight(1f),308        )309        Text(310            if (revealed) "hide" else "show", color = accent, style = PeachType.labelMono,311            modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onReveal).padding(8.dp),312        )313        CopyButton(copied, onCopy)314    }315}316317/** A field row: uppercase mono label over a value/action row, with a t3 hairline beneath (spec §5.4). */318@Composable319private fun FieldShell(320    label: String,321    content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit,322) {323    Column(324        Modifier.fillMaxWidth().padding(vertical = 10.dp).drawBehind {325            drawRect(326                color = PeachColors.T3,327                topLeft = Offset(0f, size.height - 1.dp.toPx()),328                size = Size(size.width, 1.dp.toPx()),329            )330        },331    ) {332        Text(label.uppercase(), color = PeachColors.T2, style = PeachType.labelMono.copy(letterSpacing = 0.08.em))333        Spacer(Modifier.height(6.dp))334        Row(verticalAlignment = Alignment.CenterVertically, content = content)335    }336}337338/** Accent-tinted TOTP band (spec §5.4): large Cormorant code, mono countdown, sweep ring. */339@Composable340private fun TotpBand(totpField: String, copied: Boolean, onCopy: () -> Unit) {341    val accent = LocalPeachAccent.current342    val reduceMotion = LocalReduceMotion.current343    val code by produceState(TOTPGenerator.generateCode(totpField) ?: "------") {344        while (true) {345            value = TOTPGenerator.generateCode(totpField) ?: "------"346            kotlinx.coroutines.delay(1000)347        }348    }349    val remaining by produceState(TOTPGenerator.remainingSeconds()) {350        while (true) { value = TOTPGenerator.remainingSeconds(); kotlinx.coroutines.delay(500) }351    }352    val isHot = remaining <= 5353    // Gentle pulse for the final 5s; the transition always runs but only applies when hot.354    val pulse = rememberInfiniteTransition(label = "totp-pulse")355    val pulseAlpha by pulse.animateFloat(356        initialValue = 0.55f, targetValue = 1f,357        animationSpec = infiniteRepeatable(tween(600), RepeatMode.Reverse), label = "totp-pulse-alpha",358    )359    val codeAlpha = if (isHot && !reduceMotion) pulseAlpha else 1f360361    Box(362        Modifier363            .fillMaxWidth()364            .padding(vertical = 10.dp)365            .clip(RoundedCornerShape(8.dp))366            .background(accent.copy(alpha = 0.08f))367            .border(1.dp, accent.copy(alpha = 0.20f), RoundedCornerShape(8.dp))368            .padding(horizontal = 14.dp, vertical = 10.dp),369    ) {370        Row(verticalAlignment = Alignment.CenterVertically) {371            Column(Modifier.weight(1f)) {372                Text(373                    "ONE-TIME CODE",374                    color = accent.copy(alpha = 0.70f),375                    style = PeachType.labelMono.copy(letterSpacing = 0.08.em),376                )377                val spaced = if (code.length == 6) "${code.substring(0, 3)} ${code.substring(3)}" else code378                Text(379                    spaced,380                    color = if (isHot) PeachColors.Breach else accent,381                    style = PeachType.totpCode,382                    modifier = Modifier.graphicsLayer { alpha = codeAlpha },383                )384            }385            Text("${remaining}s", color = PeachColors.T2, style = PeachType.totpCountdown)386            Spacer(Modifier.width(12.dp))387            TOTPRing(size = 28.dp)388            Spacer(Modifier.width(8.dp))389            CopyButton(copied, onCopy)390        }391    }392}393394/**395 * Copy button with the two-effect copy feedback (spec §4.4): a diagonal sheen396 * sweeps once over ~600ms and an accent drain bar fills 0→100% over 1.4s. Both397 * collapse instantly when the copied latch clears, and are skipped under398 * reduce-motion.399 */400@Composable401private fun CopyButton(copied: Boolean, onCopy: () -> Unit) {402    val accent = LocalPeachAccent.current403    val reduceMotion = LocalReduceMotion.current404    val animate = copied && !reduceMotion405    val drain by animateFloatAsState(406        targetValue = if (copied) 1f else 0f,407        animationSpec = if (animate) tween(1400, easing = LinearEasing) else tween(0),408        label = "copy-drain",409    )410    val sheen by animateFloatAsState(411        targetValue = if (copied) 1f else 0f,412        animationSpec = if (animate) tween(600, easing = LinearEasing) else tween(0),413        label = "copy-sheen",414    )415    Box(416        Modifier417            .size(36.dp)418            .clip(RoundedCornerShape(6.dp))419            .background(PeachColors.S2)420            .clickable(onClick = onCopy)421            .drawBehind {422                if (animate && sheen < 1f) {423                    val sweepX = (sheen * 2f - 0.5f) * size.width424                    val band = size.width * 0.5f425                    drawRect(426                        brush = Brush.linearGradient(427                            colors = listOf(Color.Transparent, accent.copy(alpha = 0.35f), Color.Transparent),428                            start = Offset(sweepX - band, 0f),429                            end = Offset(sweepX + band, size.height),430                        ),431                    )432                }433                if (drain > 0f) {434                    val h = 2.dp.toPx()435                    drawRect(436                        color = accent,437                        topLeft = Offset(0f, size.height - h),438                        size = Size(size.width * drain, h),439                    )440                }441            },442        contentAlignment = Alignment.Center,443    ) {444        Icon(445            if (copied) Icons.Rounded.Check else Icons.Rounded.ContentCopy,446            contentDescription = "copy",447            tint = if (copied) accent else PeachColors.T1,448            modifier = Modifier.size(15.dp),449        )450    }451}452453private fun com.peachpasswords.vault.VaultEntry.displayDomain(): String {454    val raw = url455    if (!raw.isNullOrBlank()) {456        val cleaned = raw.replace(Regex("^https?://"), "").removePrefix("www.").substringBefore('/')457        if (cleaned.isNotEmpty()) return cleaned458    }459    return ""460}