EntryDetailScreen.kt

21.3 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.gestures.detectVerticalDragGestures16import androidx.compose.foundation.layout.Arrangement17import androidx.compose.foundation.layout.Box18import androidx.compose.foundation.layout.Column19import androidx.compose.foundation.layout.Row20import androidx.compose.foundation.layout.Spacer21import androidx.compose.foundation.layout.fillMaxSize22import androidx.compose.foundation.layout.fillMaxHeight23import androidx.compose.foundation.layout.fillMaxWidth24import androidx.compose.foundation.layout.height25import androidx.compose.foundation.layout.offset26import androidx.compose.foundation.layout.padding27import androidx.compose.foundation.layout.navigationBarsPadding28import androidx.compose.foundation.layout.size29import androidx.compose.foundation.layout.statusBarsPadding30import androidx.compose.foundation.layout.width31import androidx.compose.foundation.rememberScrollState32import androidx.compose.foundation.shape.CircleShape33import androidx.compose.foundation.shape.RoundedCornerShape34import androidx.compose.material.icons.rounded.Check35import androidx.compose.material.icons.rounded.ContentCopy36import androidx.compose.material.icons.rounded.Search37import androidx.compose.foundation.verticalScroll38import androidx.compose.material.icons.Icons39import androidx.compose.material.icons.automirrored.rounded.ArrowBack40import androidx.compose.material.icons.automirrored.rounded.ArrowForward41import androidx.compose.material.icons.outlined.DeleteOutline42import androidx.compose.material3.Icon43import androidx.compose.material3.Text44import androidx.compose.runtime.Composable45import androidx.compose.runtime.DisposableEffect46import androidx.compose.runtime.getValue47import androidx.compose.runtime.mutableStateOf48import androidx.compose.runtime.produceState49import androidx.compose.runtime.remember50import androidx.compose.runtime.setValue51import androidx.compose.ui.Alignment52import androidx.compose.ui.Modifier53import androidx.compose.ui.draw.clip54import androidx.compose.ui.draw.clipToBounds55import androidx.compose.ui.draw.drawBehind56import androidx.compose.ui.geometry.Offset57import androidx.compose.ui.geometry.Size58import androidx.compose.ui.graphics.Brush59import androidx.compose.ui.graphics.Color60import androidx.compose.ui.graphics.graphicsLayer61import androidx.compose.ui.platform.LocalContext62import androidx.compose.ui.input.pointer.pointerInput63import androidx.compose.ui.text.TextStyle64import androidx.compose.ui.text.font.FontStyle65import androidx.compose.ui.text.style.TextOverflow66import androidx.compose.ui.unit.dp67import androidx.compose.ui.unit.em68import androidx.compose.ui.unit.sp69import androidx.compose.runtime.collectAsState70import androidx.fragment.app.FragmentActivity71import androidx.hilt.navigation.compose.hiltViewModel72import com.peachpasswords.ui.PeachNav73import com.peachpasswords.ui.components.CharEnterText74import com.peachpasswords.ui.components.CopyButton75import com.peachpasswords.ui.components.FaviconInitials76import com.peachpasswords.ui.components.TOTPRing77import com.peachpasswords.ui.lock.Biometrics78import com.peachpasswords.ui.theme.LocalPeachAccent79import com.peachpasswords.ui.theme.LocalReduceMotion80import com.peachpasswords.ui.theme.peachColors81import com.peachpasswords.ui.theme.PeachType82import com.peachpasswords.ui.theme.ShellBackground83import com.peachpasswords.vault.TOTPGenerator84import com.peachpasswords.vault.hasTOTP85import com.peachpasswords.vault.isBreach86import com.peachpasswords.vault.isCard8788@Composable89fun EntryDetailScreen(90    id: String,91    onNavigate: (PeachNav) -> Unit,92    onBack: () -> Unit,93    vm: EntryDetailViewModel = hiltViewModel(),94) {95    val entry by vm.entry.collectAsState()96    val activeEntries by vm.activeEntries.collectAsState()97    val identitySuggestions by vm.identitySuggestions.collectAsState()98    val cvcRevealed by vm.cvcRevealed.collectAsState()99    var cardRevealed by remember { mutableStateOf(false) }100    val copiedField by vm.copiedField.collectAsState()101    val context = LocalContext.current102    val accent = LocalPeachAccent.current103    var confirmingDelete by remember { mutableStateOf(false) }104    var generatorOpen by remember { mutableStateOf(false) }105    var historyExpanded by remember { mutableStateOf(false) }106107    // FLAG_SECURE only while this screen is shown — blocks screenshots of secrets.108    DisposableEffect(Unit) {109        val window = (context as? FragmentActivity)?.window110        window?.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)111        onDispose { window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) }112    }113114    val e = entry115    ShellBackground {116        Box(Modifier.fillMaxSize().statusBarsPadding()) {117            Column(118                Modifier.fillMaxSize()119                    .padding(bottom = 100.dp)120                    .verticalScroll(rememberScrollState())121                    .padding(horizontal = 24.dp),122            ) {123                // Header: back · favicon+domain (or delete confirm) · trash124                Row(125                    Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 8.dp),126                    verticalAlignment = Alignment.CenterVertically,127                ) {128                    Icon(129                        Icons.AutoMirrored.Rounded.ArrowBack, contentDescription = "back", tint = peachColors.T0,130                        modifier = Modifier.size(40.dp).clip(CircleShape).clickable(onClick = onBack).padding(8.dp),131                    )132                    Box(Modifier.weight(1f), contentAlignment = Alignment.Center) {133                        when {134                            e == null -> {}135                            confirmingDelete -> Text(136                                "delete “${e.title}”?",137                                color = peachColors.Breach,138                                style = PeachType.labelMono.copy(letterSpacing = 0.08.em),139                            )140                            else -> Row(141                                verticalAlignment = Alignment.CenterVertically,142                                horizontalArrangement = Arrangement.spacedBy(8.dp),143                            ) {144                                FaviconInitials(source = e.url ?: e.title, size = 16.dp)145                                val domain = remember(e.url, e.title) { e.displayDomain() }146                                if (domain.isNotEmpty()) {147                                    Text(domain, color = peachColors.T2, style = TextStyle(fontFamily = PeachType.Mono, fontSize = 9.sp))148                                }149                            }150                        }151                    }152                    if (e != null) {153                        Icon(154                            Icons.Outlined.DeleteOutline, contentDescription = "delete",155                            tint = if (confirmingDelete) peachColors.Breach else peachColors.T1,156                            modifier = Modifier.size(40.dp).clip(CircleShape)157                                .clickable { if (confirmingDelete) vm.delete(onDone = onBack) else confirmingDelete = true }158                                .padding(8.dp),159                        )160                    }161                }162163                if (e == null) {164                    Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {165                        Text("entry not found", color = peachColors.T1, style = PeachType.bodyMono)166                    }167                    return@Column168                }169170                // D11 — breach banner strip when this entry's password is known-compromised.171                if (e.isBreach()) {172                    Row(173                        Modifier.fillMaxWidth()174                            .background(peachColors.BreachBg)175                            .padding(horizontal = 16.dp, vertical = 8.dp),176                        verticalAlignment = Alignment.CenterVertically,177                    ) {178                        Text("⚠", color = peachColors.Breach, style = PeachType.bodyMono)179                        Spacer(Modifier.width(10.dp))180                        Text(181                            "Password found in a data breach — change it now",182                            color = peachColors.Breach, style = PeachType.labelMono,183                            modifier = Modifier.weight(1f),184                        )185                        Text(186                            "Change password",187                            color = accent, style = PeachType.labelMono,188                            modifier = Modifier.clip(RoundedCornerShape(6.dp))189                                .clickable { onNavigate(PeachNav.EntryEdit(e.id)) }190                                .padding(horizontal = 6.dp, vertical = 4.dp),191                        )192                    }193                }194195                // Hero — ghost PeachScript watermark behind the entry name. The full196                // title is drawn (not just its first letter); a long title overflows197                // and clips naturally, which is the intended watermark behavior.198                Box(Modifier.fillMaxWidth().clipToBounds()) {199                    Text(200                        text = ghostWatermarkText(e.title),201                        style = TextStyle(fontFamily = PeachType.Display, fontSize = 150.sp, fontStyle = FontStyle.Italic),202                        color = peachColors.T0.copy(alpha = 0.03f),203                        maxLines = 1,204                        softWrap = false,205                        overflow = TextOverflow.Clip,206                        modifier = Modifier.align(Alignment.TopCenter).offset(y = (-16).dp),207                    )208                    Column(Modifier.fillMaxWidth().padding(top = 18.dp)) {209                        CharEnterText(210                            text = e.title,211                            style = PeachType.entryNameHero.copy(color = peachColors.T0),212                        )213                        Spacer(Modifier.height(8.dp))214                        Text(215                            text = "edit",216                            color = accent,217                            style = PeachType.labelMono,218                            modifier = Modifier.clip(RoundedCornerShape(6.dp))219                                .clickable { onNavigate(PeachNav.EntryEdit(e.id)) }220                                .padding(vertical = 4.dp),221                        )222                    }223                }224                Spacer(Modifier.height(20.dp))225226                if (e.isCard()) {227                    CardDetailFields(228                        entry = e,229                        cardRevealed = cardRevealed,230                        cvcRevealed = cvcRevealed,231                        copiedField = copiedField,232                        onToggleCardReveal = { cardRevealed = !cardRevealed },233                        onRevealCvc = {234                            val activity = context as? FragmentActivity235                            if (activity != null && Biometrics.isAvailable(context)) {236                                Biometrics.authenticate(activity, "Unlock Peach", e.title, onSuccess = vm::revealCvc)237                            } else vm.revealCvc()238                        },239                        onMaskCvc = vm::maskCvc,240                        onCopy = vm::copy,241                        copyButton = { copied, onCopy -> CopyButton(copied, onCopy) },242                    )243                } else {244                    e.username?.takeIf { it.isNotBlank() }?.let { v ->245                        EditableFieldRow(246                            label = "username", field = "username", value = v,247                            copied = copiedField == "username",248                            onCopy = { vm.copy("username", v) },249                            onSave = { vm.updateField("username", it) },250                            suggestions = identitySuggestions,251                        )252                    }253                    e.email?.takeIf { it.isNotBlank() }?.let { v ->254                        EditableFieldRow(255                            label = "email", field = "email", value = v,256                            copied = copiedField == "email",257                            onCopy = { vm.copy("email", v) },258                            onSave = { vm.updateField("email", it) },259                            suggestions = identitySuggestions,260                        )261                    }262                    e.additionalUrls?.takeIf { it.any { u -> u.isNotBlank() } }?.let { urls ->263                        AdditionalUrlRows(264                            urls = urls,265                            copiedField = copiedField,266                            onCopy = { key, value -> vm.copy(key, value) },267                        )268                    }269                    e.password?.takeIf { it.isNotBlank() }?.let { pw ->270                        EditablePasswordRow(271                            value = pw,272                            copied = copiedField == "password",273                            entryTitle = e.title,274                            onCopy = { vm.copy("password", pw) },275                            onSave = { vm.updateField("password", it) },276                            onGenerate = { generatorOpen = true },277                        )278                    }279                    val history = e.passwordHistory.orEmpty()280                    if (history.isNotEmpty()) {281                        PasswordHistoryToggle(282                            count = history.size,283                            expanded = historyExpanded,284                            onToggle = { historyExpanded = !historyExpanded },285                        )286                        AnimatedVisibility(visible = historyExpanded) {287                            Column(Modifier.padding(top = 8.dp, bottom = 6.dp)) {288                                PasswordHistoryList(289                                    history = history,290                                    onRestore = { oldPw -> vm.restorePassword(e.id, oldPw) },291                                    onCopy = { oldPw -> vm.copy("password", oldPw) },292                                )293                            }294                        }295                    }296                    if (e.hasTOTP()) {297                        Spacer(Modifier.height(4.dp))298                        TotpBandEditable(299                            totpField = e.totp!!,300                            copied = copiedField == "totp",301                            onCopy = vm::copyTotp,302                            onSaveSecret = { newSecret -> vm.updateField("totp", newSecret) },303                        )304                    }305                }306                e.notes?.takeIf { it.isNotBlank() }?.let { v ->307                    EditableFieldRow(308                        label = "notes", field = "notes", value = v,309                        copied = copiedField == "notes",310                        onCopy = { vm.copy("notes", v) },311                        onSave = { vm.updateField("notes", it) },312                        mono = false, singleLine = false,313                    )314                }315                e.tags?.takeIf { it.isNotEmpty() }?.let { tags ->316                    DetailTagRow(317                        tags = tags,318                        onEditTags = { onNavigate(PeachNav.EntryEdit(e.id)) },319                    )320                }321322                Spacer(Modifier.height(24.dp))323            }324325            if (e != null) {326                EntryDetailSearchStrip(327                    currentIndex = activeEntries.indexOfFirst { it.id == e.id },328                    totalEntries = activeEntries.size,329                    onOpenList = { onNavigate(PeachNav.VaultList) },330                    onPrevious = { vm.adjacentDestination(-1)?.let(onNavigate) },331                    onNext = { vm.adjacentDestination(1)?.let(onNavigate) },332                    modifier = Modifier.align(Alignment.BottomCenter),333                )334            }335336            if (generatorOpen) {337                GeneratorSheet(338                    copied = copiedField == "genDraft",339                    onCopy = { draft -> vm.copy("genDraft", draft) },340                    onUse = { draft -> vm.applyGeneratedPassword(draft) { generatorOpen = false } },341                    onDismiss = { generatorOpen = false },342                )343            }344        }345    }346}347348@Composable349private fun EntryDetailSearchStrip(350    currentIndex: Int,351    totalEntries: Int,352    onOpenList: () -> Unit,353    onPrevious: () -> Unit,354    onNext: () -> Unit,355    modifier: Modifier = Modifier,356) {357    val accent = LocalPeachAccent.current358    val hasEntries = totalEntries > 0 && currentIndex >= 0359    val counter = if (hasEntries) "${currentIndex + 1} / $totalEntries" else "0 entries"360361    Column(362        modifier363            .fillMaxWidth()364            .navigationBarsPadding()365            .padding(horizontal = 16.dp, vertical = 12.dp),366    ) {367        Row(368            Modifier369                .fillMaxWidth()370                .height(56.dp)371                .clip(RoundedCornerShape(16.dp))372                .background(peachColors.S1)373                .border(1.dp, peachColors.T3, RoundedCornerShape(16.dp))374                .padding(horizontal = 12.dp),375            verticalAlignment = Alignment.CenterVertically,376        ) {377            Row(378                Modifier379                    .weight(1f)380                    .fillMaxHeight()381                    .clickable(onClick = onOpenList)382                    .pointerInput(onOpenList) {383                        var opened = false384                        detectVerticalDragGestures(385                            onDragEnd = { opened = false },386                            onDragCancel = { opened = false },387                        ) { _, dragAmount ->388                            if (!opened && dragAmount < -4f) {389                                opened = true390                                onOpenList()391                            }392                        }393                    },394                verticalAlignment = Alignment.CenterVertically,395            ) {396                Icon(397                    Icons.Rounded.Search,398                    contentDescription = null,399                    tint = accent,400                    modifier = Modifier.size(14.dp),401                )402                Spacer(Modifier.width(8.dp))403                Text(404                    "search vault...",405                    color = peachColors.T2,406                    style = PeachType.searchInput,407                    modifier = Modifier.weight(1f),408                )409                Text(410                    counter,411                    color = peachColors.T2,412                    style = PeachType.labelMono,413                )414            }415            Spacer(Modifier.width(8.dp))416            Icon(417                Icons.AutoMirrored.Rounded.ArrowBack,418                contentDescription = "Previous entry",419                tint = if (hasEntries) peachColors.T0 else peachColors.T2,420                modifier = Modifier421                    .size(38.dp)422                    .clip(CircleShape)423                    .clickable(enabled = hasEntries, onClick = onPrevious)424                    .padding(9.dp),425            )426            Icon(427                Icons.AutoMirrored.Rounded.ArrowForward,428                contentDescription = "Next entry",429                tint = if (hasEntries) peachColors.T0 else peachColors.T2,430                modifier = Modifier431                    .size(38.dp)432                    .clip(CircleShape)433                    .clickable(enabled = hasEntries, onClick = onNext)434                    .padding(9.dp),435            )436        }437    }438}439440/** A field row: uppercase mono label over a value/action row, with a t3 hairline beneath (spec §5.4). */441@Composable442internal fun FieldShell(443    label: String,444    content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit,445) {446    val hairline = peachColors.T3447    Column(448        Modifier.fillMaxWidth().padding(vertical = 10.dp).drawBehind {449            drawRect(450                color = hairline,451                topLeft = Offset(0f, size.height - 1.dp.toPx()),452                size = Size(size.width, 1.dp.toPx()),453            )454        },455    ) {456        Text(label.uppercase(), color = peachColors.T2, style = PeachType.labelMono.copy(letterSpacing = 0.08.em))457        Spacer(Modifier.height(6.dp))458        Row(verticalAlignment = Alignment.CenterVertically, content = content)459    }460}461462/**463 * Text for the ghost PeachScript watermark behind the entry name: the full title,464 * falling back to "P" for a blank title so the hero never renders empty.465 */466internal fun ghostWatermarkText(title: String): String = title.ifBlank { "P" }467468private fun com.peachpasswords.vault.VaultEntry.displayDomain(): String {469    val raw = url470    if (!raw.isNullOrBlank()) {471        val cleaned = raw.replace(Regex("^https?://"), "").removePrefix("www.").substringBefore('/')472        if (cleaned.isNotEmpty()) return cleaned473    }474    return ""475}