EntryDetailScreen.kt

17.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.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 identitySuggestions by vm.identitySuggestions.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 { v ->226                        EditableFieldRow(227                            label = "username", field = "username", value = v,228                            copied = copiedField == "username",229                            onCopy = { vm.copy("username", v) },230                            onSave = { vm.updateField("username", it) },231                            suggestions = identitySuggestions,232                        )233                    }234                    e.email?.takeIf { it.isNotBlank() }?.let { v ->235                        EditableFieldRow(236                            label = "email", field = "email", value = v,237                            copied = copiedField == "email",238                            onCopy = { vm.copy("email", v) },239                            onSave = { vm.updateField("email", it) },240                            suggestions = identitySuggestions,241                        )242                    }243                    e.additionalUrls?.takeIf { it.any { u -> u.isNotBlank() } }?.let { urls ->244                        AdditionalUrlRows(245                            urls = urls,246                            copiedField = copiedField,247                            onCopy = { key, value -> vm.copy(key, value) },248                        )249                    }250                    e.password?.takeIf { it.isNotBlank() }?.let { pw ->251                        EditablePasswordRow(252                            value = pw,253                            copied = copiedField == "password",254                            entryTitle = e.title,255                            onCopy = { vm.copy("password", pw) },256                            onSave = { vm.updateField("password", it) },257                            onGenerate = { generatorOpen = true },258                        )259                    }260                    if (e.hasTOTP()) {261                        Spacer(Modifier.height(4.dp))262                        TotpBand(totpField = e.totp!!, copied = copiedField == "totp", onCopy = vm::copyTotp)263                    }264                }265                e.notes?.takeIf { it.isNotBlank() }?.let { v ->266                    EditableFieldRow(267                        label = "notes", field = "notes", value = v,268                        copied = copiedField == "notes",269                        onCopy = { vm.copy("notes", v) },270                        onSave = { vm.updateField("notes", it) },271                        mono = false, singleLine = false,272                    )273                }274                e.tags?.takeIf { it.isNotEmpty() }?.let { tags ->275                    DetailTagRow(276                        tags = tags,277                        onEditTags = { onNavigate(PeachNav.EntryEdit(e.id)) },278                    )279                }280281                Spacer(Modifier.height(48.dp))282            }283284            if (generatorOpen) {285                GeneratorSheet(286                    copied = copiedField == "genDraft",287                    onCopy = { draft -> vm.copy("genDraft", draft) },288                    onUse = { draft -> vm.applyGeneratedPassword(draft) { generatorOpen = false } },289                    onDismiss = { generatorOpen = false },290                )291            }292        }293    }294}295296/** A field row: uppercase mono label over a value/action row, with a t3 hairline beneath (spec §5.4). */297@Composable298internal fun FieldShell(299    label: String,300    content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit,301) {302    Column(303        Modifier.fillMaxWidth().padding(vertical = 10.dp).drawBehind {304            drawRect(305                color = PeachColors.T3,306                topLeft = Offset(0f, size.height - 1.dp.toPx()),307                size = Size(size.width, 1.dp.toPx()),308            )309        },310    ) {311        Text(label.uppercase(), color = PeachColors.T2, style = PeachType.labelMono.copy(letterSpacing = 0.08.em))312        Spacer(Modifier.height(6.dp))313        Row(verticalAlignment = Alignment.CenterVertically, content = content)314    }315}316317/** Accent-tinted TOTP band (spec §5.4): large Cormorant code, mono countdown, sweep ring. */318@Composable319private fun TotpBand(totpField: String, copied: Boolean, onCopy: () -> Unit) {320    val accent = LocalPeachAccent.current321    val reduceMotion = LocalReduceMotion.current322    val code by produceState(TOTPGenerator.generateCode(totpField) ?: "------") {323        while (true) {324            value = TOTPGenerator.generateCode(totpField) ?: "------"325            kotlinx.coroutines.delay(1000)326        }327    }328    val remaining by produceState(TOTPGenerator.remainingSeconds()) {329        while (true) { value = TOTPGenerator.remainingSeconds(); kotlinx.coroutines.delay(500) }330    }331    val isHot = remaining <= 5332    // Gentle pulse for the final 5s; the transition always runs but only applies when hot.333    val pulse = rememberInfiniteTransition(label = "totp-pulse")334    val pulseAlpha by pulse.animateFloat(335        initialValue = 0.55f, targetValue = 1f,336        animationSpec = infiniteRepeatable(tween(600), RepeatMode.Reverse), label = "totp-pulse-alpha",337    )338    val codeAlpha = if (isHot && !reduceMotion) pulseAlpha else 1f339340    Box(341        Modifier342            .fillMaxWidth()343            .padding(vertical = 10.dp)344            .clip(RoundedCornerShape(8.dp))345            .background(accent.copy(alpha = 0.08f))346            .border(1.dp, accent.copy(alpha = 0.20f), RoundedCornerShape(8.dp))347            .padding(horizontal = 14.dp, vertical = 10.dp),348    ) {349        Row(verticalAlignment = Alignment.CenterVertically) {350            Column(Modifier.weight(1f)) {351                Text(352                    "ONE-TIME CODE",353                    color = accent.copy(alpha = 0.70f),354                    style = PeachType.labelMono.copy(letterSpacing = 0.08.em),355                )356                val spaced = if (code.length == 6) "${code.substring(0, 3)} ${code.substring(3)}" else code357                Text(358                    spaced,359                    color = if (isHot) PeachColors.Breach else accent,360                    style = PeachType.totpCode,361                    modifier = Modifier.graphicsLayer { alpha = codeAlpha },362                )363            }364            Text("${remaining}s", color = PeachColors.T2, style = PeachType.totpCountdown)365            Spacer(Modifier.width(12.dp))366            TOTPRing(size = 28.dp)367            Spacer(Modifier.width(8.dp))368            CopyButton(copied, onCopy)369        }370    }371}372373private fun com.peachpasswords.vault.VaultEntry.displayDomain(): String {374    val raw = url375    if (!raw.isNullOrBlank()) {376        val cleaned = raw.replace(Regex("^https?://"), "").removePrefix("www.").substringBefore('/')377        if (cleaned.isNotEmpty()) return cleaned378    }379    return ""380}