EntryDetailScreen.kt

19.2 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.password?.takeIf { it.isNotBlank() }?.let { pw ->230                        PasswordRow(231                            value = pw,232                            revealed = revealed,233                            copied = copiedField == "password",234                            onReveal = {235                                if (revealed) vm.mask()236                                else {237                                    val activity = context as? FragmentActivity238                                    if (activity != null && Biometrics.isAvailable(context)) {239                                        Biometrics.authenticate(activity, "Unlock Peach", e.title, onSuccess = vm::reveal)240                                    } else vm.reveal()241                                }242                            },243                            onCopy = { vm.copy("password", pw) },244                        )245                    }246                    if (e.hasTOTP()) {247                        Spacer(Modifier.height(4.dp))248                        TotpBand(totpField = e.totp!!, copied = copiedField == "totp", onCopy = vm::copyTotp)249                    }250                }251                e.notes?.takeIf { it.isNotBlank() }?.let {252                    FieldRow("notes", it, copiedField == "notes", mono = false) { vm.copy("notes", it) }253                }254                e.tags?.takeIf { it.isNotEmpty() }?.let { tags ->255                    DetailTagRow(256                        tags = tags,257                        onEditTags = { onNavigate(PeachNav.EntryEdit(e.id)) },258                    )259                }260261                Spacer(Modifier.height(48.dp))262            }263        }264    }265}266267@Composable268private fun FieldRow(269    label: String,270    value: String,271    copied: Boolean,272    mono: Boolean = true,273    onCopy: () -> Unit,274) {275    FieldShell(label) {276        Text(277            value,278            color = PeachColors.T0,279            style = if (mono) PeachType.bodyMono else PeachType.body,280            modifier = Modifier.weight(1f),281        )282        CopyButton(copied, onCopy)283    }284}285286@Composable287private fun PasswordRow(288    value: String,289    revealed: Boolean,290    copied: Boolean,291    onReveal: () -> Unit,292    onCopy: () -> Unit,293) {294    val accent = LocalPeachAccent.current295    FieldShell("password") {296        Text(297            text = if (revealed) value else "•".repeat(value.length.coerceIn(8, 16)),298            color = PeachColors.T0,299            style = PeachType.bodyMono,300            modifier = Modifier.weight(1f),301        )302        Text(303            if (revealed) "hide" else "show", color = accent, style = PeachType.labelMono,304            modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onReveal).padding(8.dp),305        )306        CopyButton(copied, onCopy)307    }308}309310/** A field row: uppercase mono label over a value/action row, with a t3 hairline beneath (spec §5.4). */311@Composable312private fun FieldShell(313    label: String,314    content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit,315) {316    Column(317        Modifier.fillMaxWidth().padding(vertical = 10.dp).drawBehind {318            drawRect(319                color = PeachColors.T3,320                topLeft = Offset(0f, size.height - 1.dp.toPx()),321                size = Size(size.width, 1.dp.toPx()),322            )323        },324    ) {325        Text(label.uppercase(), color = PeachColors.T2, style = PeachType.labelMono.copy(letterSpacing = 0.08.em))326        Spacer(Modifier.height(6.dp))327        Row(verticalAlignment = Alignment.CenterVertically, content = content)328    }329}330331/** Accent-tinted TOTP band (spec §5.4): large Cormorant code, mono countdown, sweep ring. */332@Composable333private fun TotpBand(totpField: String, copied: Boolean, onCopy: () -> Unit) {334    val accent = LocalPeachAccent.current335    val reduceMotion = LocalReduceMotion.current336    val code by produceState(TOTPGenerator.generateCode(totpField) ?: "------") {337        while (true) {338            value = TOTPGenerator.generateCode(totpField) ?: "------"339            kotlinx.coroutines.delay(1000)340        }341    }342    val remaining by produceState(TOTPGenerator.remainingSeconds()) {343        while (true) { value = TOTPGenerator.remainingSeconds(); kotlinx.coroutines.delay(500) }344    }345    val isHot = remaining <= 5346    // Gentle pulse for the final 5s; the transition always runs but only applies when hot.347    val pulse = rememberInfiniteTransition(label = "totp-pulse")348    val pulseAlpha by pulse.animateFloat(349        initialValue = 0.55f, targetValue = 1f,350        animationSpec = infiniteRepeatable(tween(600), RepeatMode.Reverse), label = "totp-pulse-alpha",351    )352    val codeAlpha = if (isHot && !reduceMotion) pulseAlpha else 1f353354    Box(355        Modifier356            .fillMaxWidth()357            .padding(vertical = 10.dp)358            .clip(RoundedCornerShape(8.dp))359            .background(accent.copy(alpha = 0.08f))360            .border(1.dp, accent.copy(alpha = 0.20f), RoundedCornerShape(8.dp))361            .padding(horizontal = 14.dp, vertical = 10.dp),362    ) {363        Row(verticalAlignment = Alignment.CenterVertically) {364            Column(Modifier.weight(1f)) {365                Text(366                    "ONE-TIME CODE",367                    color = accent.copy(alpha = 0.70f),368                    style = PeachType.labelMono.copy(letterSpacing = 0.08.em),369                )370                val spaced = if (code.length == 6) "${code.substring(0, 3)} ${code.substring(3)}" else code371                Text(372                    spaced,373                    color = if (isHot) PeachColors.Breach else accent,374                    style = PeachType.totpCode,375                    modifier = Modifier.graphicsLayer { alpha = codeAlpha },376                )377            }378            Text("${remaining}s", color = PeachColors.T2, style = PeachType.totpCountdown)379            Spacer(Modifier.width(12.dp))380            TOTPRing(size = 28.dp)381            Spacer(Modifier.width(8.dp))382            CopyButton(copied, onCopy)383        }384    }385}386387/**388 * Copy button with the two-effect copy feedback (spec §4.4): a diagonal sheen389 * sweeps once over ~600ms and an accent drain bar fills 0→100% over 1.4s. Both390 * collapse instantly when the copied latch clears, and are skipped under391 * reduce-motion.392 */393@Composable394private fun CopyButton(copied: Boolean, onCopy: () -> Unit) {395    val accent = LocalPeachAccent.current396    val reduceMotion = LocalReduceMotion.current397    val animate = copied && !reduceMotion398    val drain by animateFloatAsState(399        targetValue = if (copied) 1f else 0f,400        animationSpec = if (animate) tween(1400, easing = LinearEasing) else tween(0),401        label = "copy-drain",402    )403    val sheen by animateFloatAsState(404        targetValue = if (copied) 1f else 0f,405        animationSpec = if (animate) tween(600, easing = LinearEasing) else tween(0),406        label = "copy-sheen",407    )408    Box(409        Modifier410            .size(36.dp)411            .clip(RoundedCornerShape(6.dp))412            .background(PeachColors.S2)413            .clickable(onClick = onCopy)414            .drawBehind {415                if (animate && sheen < 1f) {416                    val sweepX = (sheen * 2f - 0.5f) * size.width417                    val band = size.width * 0.5f418                    drawRect(419                        brush = Brush.linearGradient(420                            colors = listOf(Color.Transparent, accent.copy(alpha = 0.35f), Color.Transparent),421                            start = Offset(sweepX - band, 0f),422                            end = Offset(sweepX + band, size.height),423                        ),424                    )425                }426                if (drain > 0f) {427                    val h = 2.dp.toPx()428                    drawRect(429                        color = accent,430                        topLeft = Offset(0f, size.height - h),431                        size = Size(size.width * drain, h),432                    )433                }434            },435        contentAlignment = Alignment.Center,436    ) {437        Icon(438            if (copied) Icons.Rounded.Check else Icons.Rounded.ContentCopy,439            contentDescription = "copy",440            tint = if (copied) accent else PeachColors.T1,441            modifier = Modifier.size(15.dp),442        )443    }444}445446private fun com.peachpasswords.vault.VaultEntry.displayDomain(): String {447    val raw = url448    if (!raw.isNullOrBlank()) {449        val cleaned = raw.replace(Regex("^https?://"), "").removePrefix("www.").substringBefore('/')450        if (cleaned.isNotEmpty()) return cleaned451    }452    return ""453}