EntryDetailScreen.kt

18.2 KB · raw

1package com.peachpasswords.ui.vault23import android.view.WindowManager4import androidx.compose.animation.AnimatedVisibility5import androidx.compose.animation.core.LinearEasing6import androidx.compose.animation.core.RepeatMode7import androidx.compose.animation.core.animateFloat8import androidx.compose.animation.core.animateFloatAsState9import androidx.compose.animation.core.infiniteRepeatable10import androidx.compose.animation.core.rememberInfiniteTransition11import androidx.compose.animation.core.tween12import androidx.compose.foundation.background13import androidx.compose.foundation.border14import androidx.compose.foundation.clickable15import androidx.compose.foundation.layout.Arrangement16import androidx.compose.foundation.layout.Box17import androidx.compose.foundation.layout.Column18import androidx.compose.foundation.layout.Row19import androidx.compose.foundation.layout.Spacer20import androidx.compose.foundation.layout.fillMaxSize21import androidx.compose.foundation.layout.fillMaxWidth22import androidx.compose.foundation.layout.height23import androidx.compose.foundation.layout.offset24import androidx.compose.foundation.layout.padding25import androidx.compose.foundation.layout.size26import androidx.compose.foundation.layout.statusBarsPadding27import androidx.compose.foundation.layout.width28import androidx.compose.foundation.rememberScrollState29import androidx.compose.foundation.shape.CircleShape30import androidx.compose.foundation.shape.RoundedCornerShape31import androidx.compose.material.icons.rounded.Check32import androidx.compose.material.icons.rounded.ContentCopy33import androidx.compose.foundation.verticalScroll34import androidx.compose.material.icons.Icons35import androidx.compose.material.icons.automirrored.rounded.ArrowBack36import androidx.compose.material.icons.outlined.DeleteOutline37import androidx.compose.material3.Icon38import androidx.compose.material3.Text39import androidx.compose.runtime.Composable40import androidx.compose.runtime.DisposableEffect41import androidx.compose.runtime.getValue42import androidx.compose.runtime.mutableStateOf43import androidx.compose.runtime.produceState44import androidx.compose.runtime.remember45import androidx.compose.runtime.setValue46import androidx.compose.ui.Alignment47import androidx.compose.ui.Modifier48import androidx.compose.ui.draw.clip49import androidx.compose.ui.draw.drawBehind50import androidx.compose.ui.geometry.Offset51import androidx.compose.ui.geometry.Size52import androidx.compose.ui.graphics.Brush53import androidx.compose.ui.graphics.Color54import androidx.compose.ui.graphics.graphicsLayer55import androidx.compose.ui.platform.LocalContext56import androidx.compose.ui.text.TextStyle57import androidx.compose.ui.unit.dp58import androidx.compose.ui.unit.em59import androidx.compose.ui.unit.sp60import androidx.compose.runtime.collectAsState61import androidx.fragment.app.FragmentActivity62import androidx.hilt.navigation.compose.hiltViewModel63import com.peachpasswords.ui.PeachNav64import com.peachpasswords.ui.components.CharEnterText65import com.peachpasswords.ui.components.CopyButton66import com.peachpasswords.ui.components.FaviconInitials67import com.peachpasswords.ui.components.TOTPRing68import com.peachpasswords.ui.lock.Biometrics69import com.peachpasswords.ui.theme.LocalPeachAccent70import com.peachpasswords.ui.theme.LocalReduceMotion71import com.peachpasswords.ui.theme.PeachColors72import com.peachpasswords.ui.theme.PeachType73import com.peachpasswords.ui.theme.ShellBackground74import com.peachpasswords.vault.TOTPGenerator75import com.peachpasswords.vault.hasTOTP76import com.peachpasswords.vault.isBreach77import com.peachpasswords.vault.isCard7879@Composable80fun EntryDetailScreen(81    id: String,82    onNavigate: (PeachNav) -> Unit,83    onBack: () -> Unit,84    vm: EntryDetailViewModel = hiltViewModel(),85) {86    val entry by vm.entry.collectAsState()87    val identitySuggestions by vm.identitySuggestions.collectAsState()88    val cvcRevealed by vm.cvcRevealed.collectAsState()89    var cardRevealed by remember { mutableStateOf(false) }90    val copiedField by vm.copiedField.collectAsState()91    val context = LocalContext.current92    val accent = LocalPeachAccent.current93    var confirmingDelete by remember { mutableStateOf(false) }94    var generatorOpen by remember { mutableStateOf(false) }95    var historyExpanded by remember { mutableStateOf(false) }9697    // FLAG_SECURE only while this screen is shown — blocks screenshots of secrets.98    DisposableEffect(Unit) {99        val window = (context as? FragmentActivity)?.window100        window?.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)101        onDispose { window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) }102    }103104    val e = entry105    ShellBackground {106        Column(Modifier.fillMaxSize().statusBarsPadding()) {107            // Header: back · favicon+domain (or delete confirm) · trash108            Row(109                Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 8.dp),110                verticalAlignment = Alignment.CenterVertically,111            ) {112                Icon(113                    Icons.AutoMirrored.Rounded.ArrowBack, contentDescription = "back", tint = PeachColors.T0,114                    modifier = Modifier.size(40.dp).clip(CircleShape).clickable(onClick = onBack).padding(8.dp),115                )116                Box(Modifier.weight(1f), contentAlignment = Alignment.Center) {117                    when {118                        e == null -> {}119                        confirmingDelete -> Text(120                            "delete “${e.title}”?",121                            color = PeachColors.Breach,122                            style = PeachType.labelMono.copy(letterSpacing = 0.08.em),123                        )124                        else -> Row(125                            verticalAlignment = Alignment.CenterVertically,126                            horizontalArrangement = Arrangement.spacedBy(8.dp),127                        ) {128                            FaviconInitials(source = e.url ?: e.title, size = 16.dp)129                            val domain = remember(e.url, e.title) { e.displayDomain() }130                            if (domain.isNotEmpty()) {131                                Text(domain, color = PeachColors.T2, style = TextStyle(fontFamily = PeachType.Mono, fontSize = 9.sp))132                            }133                        }134                    }135                }136                if (e != null) {137                    Icon(138                        Icons.Outlined.DeleteOutline, contentDescription = "delete",139                        tint = if (confirmingDelete) PeachColors.Breach else PeachColors.T1,140                        modifier = Modifier.size(40.dp).clip(CircleShape)141                            .clickable { if (confirmingDelete) vm.delete(onDone = onBack) else confirmingDelete = true }142                            .padding(8.dp),143                    )144                }145            }146147            if (e == null) {148                Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {149                    Text("entry not found", color = PeachColors.T1, style = PeachType.bodyMono)150                }151                return@Column152            }153154            // D11 — breach banner strip when this entry's password is known-compromised.155            if (e.isBreach()) {156                Row(157                    Modifier.fillMaxWidth()158                        .background(PeachColors.BreachBg)159                        .padding(horizontal = 16.dp, vertical = 8.dp),160                    verticalAlignment = Alignment.CenterVertically,161                ) {162                    Text("⚠", color = PeachColors.Breach, style = PeachType.bodyMono)163                    Spacer(Modifier.width(10.dp))164                    Text(165                        "Password found in a data breach — change it now",166                        color = PeachColors.Breach, style = PeachType.labelMono,167                        modifier = Modifier.weight(1f),168                    )169                    Text(170                        "Change password",171                        color = accent, style = PeachType.labelMono,172                        modifier = Modifier.clip(RoundedCornerShape(6.dp))173                            .clickable { onNavigate(PeachNav.EntryEdit(e.id)) }174                            .padding(horizontal = 6.dp, vertical = 4.dp),175                    )176                }177            }178179            Column(180                Modifier.fillMaxSize().verticalScroll(rememberScrollState())181                    .padding(horizontal = 24.dp),182            ) {183                // Hero — ghost PeachScript watermark behind the entry name.184                Box(Modifier.fillMaxWidth()) {185                    Text(186                        text = e.title.firstOrNull()?.uppercase() ?: "P",187                        style = TextStyle(fontFamily = PeachType.Script, fontSize = 140.sp),188                        color = PeachColors.T0.copy(alpha = 0.03f),189                        modifier = Modifier.align(Alignment.TopCenter).offset(y = (-16).dp),190                    )191                    Column(Modifier.fillMaxWidth().padding(top = 18.dp)) {192                        CharEnterText(193                            text = e.title,194                            style = PeachType.entryNameHero.copy(color = PeachColors.T0),195                        )196                        Spacer(Modifier.height(8.dp))197                        Text(198                            text = "edit",199                            color = accent,200                            style = PeachType.labelMono,201                            modifier = Modifier.clip(RoundedCornerShape(6.dp))202                                .clickable { onNavigate(PeachNav.EntryEdit(e.id)) }203                                .padding(vertical = 4.dp),204                        )205                    }206                }207                Spacer(Modifier.height(20.dp))208209                if (e.isCard()) {210                    CardDetailFields(211                        entry = e,212                        cardRevealed = cardRevealed,213                        cvcRevealed = cvcRevealed,214                        copiedField = copiedField,215                        onToggleCardReveal = { cardRevealed = !cardRevealed },216                        onRevealCvc = {217                            val activity = context as? FragmentActivity218                            if (activity != null && Biometrics.isAvailable(context)) {219                                Biometrics.authenticate(activity, "Unlock Peach", e.title, onSuccess = vm::revealCvc)220                            } else vm.revealCvc()221                        },222                        onMaskCvc = vm::maskCvc,223                        onCopy = vm::copy,224                        copyButton = { copied, onCopy -> CopyButton(copied, onCopy) },225                    )226                } else {227                    e.username?.takeIf { it.isNotBlank() }?.let { v ->228                        EditableFieldRow(229                            label = "username", field = "username", value = v,230                            copied = copiedField == "username",231                            onCopy = { vm.copy("username", v) },232                            onSave = { vm.updateField("username", it) },233                            suggestions = identitySuggestions,234                        )235                    }236                    e.email?.takeIf { it.isNotBlank() }?.let { v ->237                        EditableFieldRow(238                            label = "email", field = "email", value = v,239                            copied = copiedField == "email",240                            onCopy = { vm.copy("email", v) },241                            onSave = { vm.updateField("email", it) },242                            suggestions = identitySuggestions,243                        )244                    }245                    e.additionalUrls?.takeIf { it.any { u -> u.isNotBlank() } }?.let { urls ->246                        AdditionalUrlRows(247                            urls = urls,248                            copiedField = copiedField,249                            onCopy = { key, value -> vm.copy(key, value) },250                        )251                    }252                    e.password?.takeIf { it.isNotBlank() }?.let { pw ->253                        EditablePasswordRow(254                            value = pw,255                            copied = copiedField == "password",256                            entryTitle = e.title,257                            onCopy = { vm.copy("password", pw) },258                            onSave = { vm.updateField("password", it) },259                            onGenerate = { generatorOpen = true },260                        )261                    }262                    val history = e.passwordHistory.orEmpty()263                    if (history.isNotEmpty()) {264                        PasswordHistoryToggle(265                            count = history.size,266                            expanded = historyExpanded,267                            onToggle = { historyExpanded = !historyExpanded },268                        )269                        AnimatedVisibility(visible = historyExpanded) {270                            Column(Modifier.padding(top = 8.dp, bottom = 6.dp)) {271                                PasswordHistoryList(272                                    history = history,273                                    onRestore = { oldPw -> vm.restorePassword(e.id, oldPw) },274                                    onCopy = { oldPw -> vm.copy("password", oldPw) },275                                )276                            }277                        }278                    }279                    if (e.hasTOTP()) {280                        Spacer(Modifier.height(4.dp))281                        TotpBand(totpField = e.totp!!, copied = copiedField == "totp", onCopy = vm::copyTotp)282                    }283                }284                e.notes?.takeIf { it.isNotBlank() }?.let { v ->285                    EditableFieldRow(286                        label = "notes", field = "notes", value = v,287                        copied = copiedField == "notes",288                        onCopy = { vm.copy("notes", v) },289                        onSave = { vm.updateField("notes", it) },290                        mono = false, singleLine = false,291                    )292                }293                e.tags?.takeIf { it.isNotEmpty() }?.let { tags ->294                    DetailTagRow(295                        tags = tags,296                        onEditTags = { onNavigate(PeachNav.EntryEdit(e.id)) },297                    )298                }299300                Spacer(Modifier.height(48.dp))301            }302303            if (generatorOpen) {304                GeneratorSheet(305                    copied = copiedField == "genDraft",306                    onCopy = { draft -> vm.copy("genDraft", draft) },307                    onUse = { draft -> vm.applyGeneratedPassword(draft) { generatorOpen = false } },308                    onDismiss = { generatorOpen = false },309                )310            }311        }312    }313}314315/** A field row: uppercase mono label over a value/action row, with a t3 hairline beneath (spec §5.4). */316@Composable317internal fun FieldShell(318    label: String,319    content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit,320) {321    Column(322        Modifier.fillMaxWidth().padding(vertical = 10.dp).drawBehind {323            drawRect(324                color = PeachColors.T3,325                topLeft = Offset(0f, size.height - 1.dp.toPx()),326                size = Size(size.width, 1.dp.toPx()),327            )328        },329    ) {330        Text(label.uppercase(), color = PeachColors.T2, style = PeachType.labelMono.copy(letterSpacing = 0.08.em))331        Spacer(Modifier.height(6.dp))332        Row(verticalAlignment = Alignment.CenterVertically, content = content)333    }334}335336/** Accent-tinted TOTP band (spec §5.4): large Cormorant code, mono countdown, sweep ring. */337@Composable338private fun TotpBand(totpField: String, copied: Boolean, onCopy: () -> Unit) {339    val accent = LocalPeachAccent.current340    val reduceMotion = LocalReduceMotion.current341    val code by produceState(TOTPGenerator.generateCode(totpField) ?: "------") {342        while (true) {343            value = TOTPGenerator.generateCode(totpField) ?: "------"344            kotlinx.coroutines.delay(1000)345        }346    }347    val remaining by produceState(TOTPGenerator.remainingSeconds()) {348        while (true) { value = TOTPGenerator.remainingSeconds(); kotlinx.coroutines.delay(500) }349    }350    val isHot = remaining <= 5351    // Gentle pulse for the final 5s; the transition always runs but only applies when hot.352    val pulse = rememberInfiniteTransition(label = "totp-pulse")353    val pulseAlpha by pulse.animateFloat(354        initialValue = 0.55f, targetValue = 1f,355        animationSpec = infiniteRepeatable(tween(600), RepeatMode.Reverse), label = "totp-pulse-alpha",356    )357    val codeAlpha = if (isHot && !reduceMotion) pulseAlpha else 1f358359    Box(360        Modifier361            .fillMaxWidth()362            .padding(vertical = 10.dp)363            .clip(RoundedCornerShape(8.dp))364            .background(accent.copy(alpha = 0.08f))365            .border(1.dp, accent.copy(alpha = 0.20f), RoundedCornerShape(8.dp))366            .padding(horizontal = 14.dp, vertical = 10.dp),367    ) {368        Row(verticalAlignment = Alignment.CenterVertically) {369            Column(Modifier.weight(1f)) {370                Text(371                    "ONE-TIME CODE",372                    color = accent.copy(alpha = 0.70f),373                    style = PeachType.labelMono.copy(letterSpacing = 0.08.em),374                )375                val spaced = if (code.length == 6) "${code.substring(0, 3)} ${code.substring(3)}" else code376                Text(377                    spaced,378                    color = if (isHot) PeachColors.Breach else accent,379                    style = PeachType.totpCode,380                    modifier = Modifier.graphicsLayer { alpha = codeAlpha },381                )382            }383            Text("${remaining}s", color = PeachColors.T2, style = PeachType.totpCountdown)384            Spacer(Modifier.width(12.dp))385            TOTPRing(size = 28.dp)386            Spacer(Modifier.width(8.dp))387            CopyButton(copied, onCopy)388        }389    }390}391392private fun com.peachpasswords.vault.VaultEntry.displayDomain(): String {393    val raw = url394    if (!raw.isNullOrBlank()) {395        val cleaned = raw.replace(Regex("^https?://"), "").removePrefix("www.").substringBefore('/')396        if (cleaned.isNotEmpty()) return cleaned397    }398    return ""399}