EntryDetailScreen.kt

17.9 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.CopyButton65import com.peachpasswords.ui.components.FaviconInitials66import com.peachpasswords.ui.components.TOTPRing67import com.peachpasswords.ui.lock.Biometrics68import com.peachpasswords.ui.theme.LocalPeachAccent69import com.peachpasswords.ui.theme.LocalReduceMotion70import com.peachpasswords.ui.theme.PeachColors71import com.peachpasswords.ui.theme.PeachType72import com.peachpasswords.ui.theme.ShellBackground73import com.peachpasswords.vault.TOTPGenerator74import com.peachpasswords.vault.hasTOTP75import com.peachpasswords.vault.isBreach76import com.peachpasswords.vault.isCard7778@Composable79fun EntryDetailScreen(80    id: String,81    onNavigate: (PeachNav) -> Unit,82    onBack: () -> Unit,83    vm: EntryDetailViewModel = hiltViewModel(),84) {85    val entry by vm.entry.collectAsState()86    val revealed by vm.revealed.collectAsState()87    val cvcRevealed by vm.cvcRevealed.collectAsState()88    var cardRevealed by remember { mutableStateOf(false) }89    val copiedField by vm.copiedField.collectAsState()90    val context = LocalContext.current91    val accent = LocalPeachAccent.current92    var confirmingDelete by remember { mutableStateOf(false) }93    var generatorOpen by remember { mutableStateOf(false) }9495    // FLAG_SECURE only while this screen is shown — blocks screenshots of secrets.96    DisposableEffect(Unit) {97        val window = (context as? FragmentActivity)?.window98        window?.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)99        onDispose { window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) }100    }101102    val e = entry103    ShellBackground {104        Column(Modifier.fillMaxSize().statusBarsPadding()) {105            // Header: back · favicon+domain (or delete confirm) · trash106            Row(107                Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 8.dp),108                verticalAlignment = Alignment.CenterVertically,109            ) {110                Icon(111                    Icons.AutoMirrored.Rounded.ArrowBack, contentDescription = "back", tint = PeachColors.T0,112                    modifier = Modifier.size(40.dp).clip(CircleShape).clickable(onClick = onBack).padding(8.dp),113                )114                Box(Modifier.weight(1f), contentAlignment = Alignment.Center) {115                    when {116                        e == null -> {}117                        confirmingDelete -> Text(118                            "delete “${e.title}”?",119                            color = PeachColors.Breach,120                            style = PeachType.labelMono.copy(letterSpacing = 0.08.em),121                        )122                        else -> Row(123                            verticalAlignment = Alignment.CenterVertically,124                            horizontalArrangement = Arrangement.spacedBy(8.dp),125                        ) {126                            FaviconInitials(source = e.url ?: e.title, size = 16.dp)127                            val domain = remember(e.url, e.title) { e.displayDomain() }128                            if (domain.isNotEmpty()) {129                                Text(domain, color = PeachColors.T2, style = TextStyle(fontFamily = PeachType.Mono, fontSize = 9.sp))130                            }131                        }132                    }133                }134                if (e != null) {135                    Icon(136                        Icons.Outlined.DeleteOutline, contentDescription = "delete",137                        tint = if (confirmingDelete) PeachColors.Breach else PeachColors.T1,138                        modifier = Modifier.size(40.dp).clip(CircleShape)139                            .clickable { if (confirmingDelete) vm.delete(onDone = onBack) else confirmingDelete = true }140                            .padding(8.dp),141                    )142                }143            }144145            if (e == null) {146                Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {147                    Text("entry not found", color = PeachColors.T1, style = PeachType.bodyMono)148                }149                return@Column150            }151152            // D11 — breach banner strip when this entry's password is known-compromised.153            if (e.isBreach()) {154                Row(155                    Modifier.fillMaxWidth()156                        .background(PeachColors.BreachBg)157                        .padding(horizontal = 16.dp, vertical = 8.dp),158                    verticalAlignment = Alignment.CenterVertically,159                ) {160                    Text("⚠", color = PeachColors.Breach, style = PeachType.bodyMono)161                    Spacer(Modifier.width(10.dp))162                    Text(163                        "Password found in a data breach — change it now",164                        color = PeachColors.Breach, style = PeachType.labelMono,165                        modifier = Modifier.weight(1f),166                    )167                    Text(168                        "Change password",169                        color = accent, style = PeachType.labelMono,170                        modifier = Modifier.clip(RoundedCornerShape(6.dp))171                            .clickable { onNavigate(PeachNav.EntryEdit(e.id)) }172                            .padding(horizontal = 6.dp, vertical = 4.dp),173                    )174                }175            }176177            Column(178                Modifier.fillMaxSize().verticalScroll(rememberScrollState())179                    .padding(horizontal = 24.dp),180            ) {181                // Hero — ghost PeachScript watermark behind the entry name.182                Box(Modifier.fillMaxWidth()) {183                    Text(184                        text = e.title.firstOrNull()?.uppercase() ?: "P",185                        style = TextStyle(fontFamily = PeachType.Script, fontSize = 140.sp),186                        color = PeachColors.T0.copy(alpha = 0.03f),187                        modifier = Modifier.align(Alignment.TopCenter).offset(y = (-16).dp),188                    )189                    Column(Modifier.fillMaxWidth().padding(top = 18.dp)) {190                        CharEnterText(191                            text = e.title,192                            style = PeachType.entryNameHero.copy(color = PeachColors.T0),193                        )194                        Spacer(Modifier.height(8.dp))195                        Text(196                            text = "edit",197                            color = accent,198                            style = PeachType.labelMono,199                            modifier = Modifier.clip(RoundedCornerShape(6.dp))200                                .clickable { onNavigate(PeachNav.EntryEdit(e.id)) }201                                .padding(vertical = 4.dp),202                        )203                    }204                }205                Spacer(Modifier.height(20.dp))206207                if (e.isCard()) {208                    CardDetailFields(209                        entry = e,210                        cardRevealed = cardRevealed,211                        cvcRevealed = cvcRevealed,212                        copiedField = copiedField,213                        onToggleCardReveal = { cardRevealed = !cardRevealed },214                        onRevealCvc = {215                            val activity = context as? FragmentActivity216                            if (activity != null && Biometrics.isAvailable(context)) {217                                Biometrics.authenticate(activity, "Unlock Peach", e.title, onSuccess = vm::revealCvc)218                            } else vm.revealCvc()219                        },220                        onMaskCvc = vm::maskCvc,221                        onCopy = vm::copy,222                        copyButton = { copied, onCopy -> CopyButton(copied, onCopy) },223                    )224                } else {225                    e.username?.takeIf { it.isNotBlank() }?.let {226                        FieldRow("username", it, copiedField == "username") { vm.copy("username", it) }227                    }228                    e.email?.takeIf { it.isNotBlank() }?.let {229                        FieldRow("email", it, copiedField == "email") { vm.copy("email", it) }230                    }231                    e.additionalUrls?.takeIf { it.any { u -> u.isNotBlank() } }?.let { urls ->232                        AdditionalUrlRows(233                            urls = urls,234                            copiedField = copiedField,235                            onCopy = { key, value -> vm.copy(key, value) },236                        )237                    }238                    e.password?.takeIf { it.isNotBlank() }?.let { pw ->239                        PasswordRow(240                            value = pw,241                            revealed = revealed,242                            copied = copiedField == "password",243                            onReveal = {244                                if (revealed) vm.mask()245                                else {246                                    val activity = context as? FragmentActivity247                                    if (activity != null && Biometrics.isAvailable(context)) {248                                        Biometrics.authenticate(activity, "Unlock Peach", e.title, onSuccess = vm::reveal)249                                    } else vm.reveal()250                                }251                            },252                            onCopy = { vm.copy("password", pw) },253                            onGenerate = { generatorOpen = true },254                        )255                    }256                    if (e.hasTOTP()) {257                        Spacer(Modifier.height(4.dp))258                        TotpBand(totpField = e.totp!!, copied = copiedField == "totp", onCopy = vm::copyTotp)259                    }260                }261                e.notes?.takeIf { it.isNotBlank() }?.let {262                    FieldRow("notes", it, copiedField == "notes", mono = false) { vm.copy("notes", it) }263                }264                e.tags?.takeIf { it.isNotEmpty() }?.let { tags ->265                    DetailTagRow(266                        tags = tags,267                        onEditTags = { onNavigate(PeachNav.EntryEdit(e.id)) },268                    )269                }270271                Spacer(Modifier.height(48.dp))272            }273274            if (generatorOpen) {275                GeneratorSheet(276                    copied = copiedField == "genDraft",277                    onCopy = { draft -> vm.copy("genDraft", draft) },278                    onUse = { draft -> vm.applyGeneratedPassword(draft) { generatorOpen = false } },279                    onDismiss = { generatorOpen = false },280                )281            }282        }283    }284}285286@Composable287private fun FieldRow(288    label: String,289    value: String,290    copied: Boolean,291    mono: Boolean = true,292    onCopy: () -> Unit,293) {294    FieldShell(label) {295        Text(296            value,297            color = PeachColors.T0,298            style = if (mono) PeachType.bodyMono else PeachType.body,299            modifier = Modifier.weight(1f),300        )301        CopyButton(copied, onCopy)302    }303}304305@Composable306private fun PasswordRow(307    value: String,308    revealed: Boolean,309    copied: Boolean,310    onReveal: () -> Unit,311    onCopy: () -> Unit,312    onGenerate: () -> Unit,313) {314    val accent = LocalPeachAccent.current315    FieldShell("password") {316        Text(317            text = if (revealed) value else "•".repeat(value.length.coerceIn(8, 16)),318            color = PeachColors.T0,319            style = PeachType.bodyMono,320            modifier = Modifier.weight(1f),321        )322        Text(323            if (revealed) "hide" else "show", color = accent, style = PeachType.labelMono,324            modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onReveal).padding(8.dp),325        )326        CopyButton(copied, onCopy)327        WrenchButton(onClick = onGenerate)328    }329}330331/** A field row: uppercase mono label over a value/action row, with a t3 hairline beneath (spec §5.4). */332@Composable333private fun FieldShell(334    label: String,335    content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit,336) {337    Column(338        Modifier.fillMaxWidth().padding(vertical = 10.dp).drawBehind {339            drawRect(340                color = PeachColors.T3,341                topLeft = Offset(0f, size.height - 1.dp.toPx()),342                size = Size(size.width, 1.dp.toPx()),343            )344        },345    ) {346        Text(label.uppercase(), color = PeachColors.T2, style = PeachType.labelMono.copy(letterSpacing = 0.08.em))347        Spacer(Modifier.height(6.dp))348        Row(verticalAlignment = Alignment.CenterVertically, content = content)349    }350}351352/** Accent-tinted TOTP band (spec §5.4): large Cormorant code, mono countdown, sweep ring. */353@Composable354private fun TotpBand(totpField: String, copied: Boolean, onCopy: () -> Unit) {355    val accent = LocalPeachAccent.current356    val reduceMotion = LocalReduceMotion.current357    val code by produceState(TOTPGenerator.generateCode(totpField) ?: "------") {358        while (true) {359            value = TOTPGenerator.generateCode(totpField) ?: "------"360            kotlinx.coroutines.delay(1000)361        }362    }363    val remaining by produceState(TOTPGenerator.remainingSeconds()) {364        while (true) { value = TOTPGenerator.remainingSeconds(); kotlinx.coroutines.delay(500) }365    }366    val isHot = remaining <= 5367    // Gentle pulse for the final 5s; the transition always runs but only applies when hot.368    val pulse = rememberInfiniteTransition(label = "totp-pulse")369    val pulseAlpha by pulse.animateFloat(370        initialValue = 0.55f, targetValue = 1f,371        animationSpec = infiniteRepeatable(tween(600), RepeatMode.Reverse), label = "totp-pulse-alpha",372    )373    val codeAlpha = if (isHot && !reduceMotion) pulseAlpha else 1f374375    Box(376        Modifier377            .fillMaxWidth()378            .padding(vertical = 10.dp)379            .clip(RoundedCornerShape(8.dp))380            .background(accent.copy(alpha = 0.08f))381            .border(1.dp, accent.copy(alpha = 0.20f), RoundedCornerShape(8.dp))382            .padding(horizontal = 14.dp, vertical = 10.dp),383    ) {384        Row(verticalAlignment = Alignment.CenterVertically) {385            Column(Modifier.weight(1f)) {386                Text(387                    "ONE-TIME CODE",388                    color = accent.copy(alpha = 0.70f),389                    style = PeachType.labelMono.copy(letterSpacing = 0.08.em),390                )391                val spaced = if (code.length == 6) "${code.substring(0, 3)} ${code.substring(3)}" else code392                Text(393                    spaced,394                    color = if (isHot) PeachColors.Breach else accent,395                    style = PeachType.totpCode,396                    modifier = Modifier.graphicsLayer { alpha = codeAlpha },397                )398            }399            Text("${remaining}s", color = PeachColors.T2, style = PeachType.totpCountdown)400            Spacer(Modifier.width(12.dp))401            TOTPRing(size = 28.dp)402            Spacer(Modifier.width(8.dp))403            CopyButton(copied, onCopy)404        }405    }406}407408private fun com.peachpasswords.vault.VaultEntry.displayDomain(): String {409    val raw = url410    if (!raw.isNullOrBlank()) {411        val cleaned = raw.replace(Regex("^https?://"), "").removePrefix("www.").substringBefore('/')412        if (cleaned.isNotEmpty()) return cleaned413    }414    return ""415}