EntryEditScreen.kt

17.4 KB · raw

1package com.peachpasswords.ui.vault23import androidx.compose.animation.core.animateDpAsState4import androidx.compose.animation.core.tween5import androidx.compose.foundation.background6import androidx.compose.foundation.border7import androidx.compose.foundation.clickable8import androidx.compose.foundation.layout.Arrangement9import androidx.compose.foundation.layout.Box10import androidx.compose.foundation.layout.Column11import androidx.compose.foundation.layout.Row12import androidx.compose.foundation.layout.Spacer13import androidx.compose.foundation.layout.fillMaxSize14import androidx.compose.foundation.layout.fillMaxWidth15import androidx.compose.foundation.layout.height16import androidx.compose.foundation.layout.offset17import androidx.compose.foundation.layout.padding18import androidx.compose.foundation.layout.statusBarsPadding19import androidx.compose.foundation.layout.width20import androidx.compose.foundation.rememberScrollState21import androidx.compose.foundation.shape.RoundedCornerShape22import androidx.compose.foundation.text.BasicTextField23import androidx.compose.foundation.verticalScroll24import androidx.compose.material3.Slider25import androidx.compose.material3.SliderDefaults26import androidx.compose.material3.Text27import androidx.compose.runtime.Composable28import androidx.compose.runtime.getValue29import androidx.compose.runtime.mutableStateOf30import androidx.compose.runtime.remember31import androidx.compose.runtime.setValue32import androidx.compose.ui.Alignment33import androidx.compose.ui.Modifier34import androidx.compose.ui.draw.clip35import androidx.compose.ui.draw.clipToBounds36import androidx.compose.ui.graphics.Color37import androidx.compose.ui.graphics.SolidColor38import androidx.compose.ui.text.TextStyle39import androidx.compose.ui.text.font.FontStyle40import androidx.compose.ui.text.font.FontWeight41import androidx.compose.ui.text.input.PasswordVisualTransformation42import androidx.compose.ui.text.input.VisualTransformation43import androidx.compose.ui.unit.dp44import androidx.compose.ui.unit.em45import androidx.compose.ui.unit.sp46import androidx.compose.runtime.collectAsState47import androidx.hilt.navigation.compose.hiltViewModel48import com.peachpasswords.ui.theme.LocalPeachAccent49import com.peachpasswords.ui.theme.PeachColors50import com.peachpasswords.ui.theme.PeachMotion51import com.peachpasswords.ui.theme.PeachRadius52import com.peachpasswords.ui.theme.PeachType53import com.peachpasswords.ui.theme.ShellBackground54import com.peachpasswords.vault.PasswordHistoryItem5556@Composable57fun EntryEditScreen(58    id: String?,59    onBack: () -> Unit,60    vm: EntryEditViewModel = hiltViewModel(),61) {62    val f by vm.form.collectAsState()63    val usernameSuggestions by vm.usernameSuggestions.collectAsState()64    val accent = LocalPeachAccent.current6566    ShellBackground {67        Column(Modifier.fillMaxSize().statusBarsPadding()) {68            Row(69                Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 18.dp),70                verticalAlignment = Alignment.CenterVertically,71                horizontalArrangement = Arrangement.SpaceBetween,72            ) {73                Text("cancel", color = PeachColors.T1, fontFamily = PeachType.Mono, fontSize = 12.sp,74                    modifier = Modifier.clip(RoundedCornerShape(8.dp)).clickable(onClick = onBack).padding(8.dp))75                Text(if (vm.isNew) "new entry" else "edit", color = PeachColors.T1,76                    fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 16.sp)77                Text("save", color = accent, fontFamily = PeachType.Mono, fontSize = 13.sp,78                    modifier = Modifier.clip(RoundedCornerShape(8.dp)).clickable { vm.save(onBack) }.padding(8.dp))79            }8081            Box(Modifier.fillMaxSize()) {82                // Ghost PeachScript watermark behind the form (matches the detail hero).83                if (f.title.isNotBlank()) {84                    Text(85                        text = f.title.first().uppercase(),86                        style = TextStyle(fontFamily = PeachType.Script, fontSize = 140.sp),87                        color = PeachColors.T0.copy(alpha = 0.03f),88                        modifier = Modifier.align(Alignment.TopEnd).offset(x = (-16).dp, y = 8.dp),89                    )90                }91                Column(92                    Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 22.dp),93                ) {94                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {95                    listOf("login", "note", "card").forEach { t ->96                        EntryTypePill(t, f.type == t) { vm.setType(t) }97                    }98                }99                Spacer(Modifier.height(18.dp))100101                Field("title", f.title, vm::setTitle)102                if (f.type == "login") {103                    Field("url", f.url, vm::setUrl)104                    IdentitySuggestField("username", f.username, usernameSuggestions, vm::setUsername)105                    IdentitySuggestField("email", f.email, usernameSuggestions, vm::setEmail)106                    PasswordField(107                        value = f.password,108                        show = f.showPassword,109                        onChange = vm::setPassword,110                        onToggleShow = vm::toggleShowPassword,111                        onToggleGenerator = vm::toggleGenerator,112                    )113                    GeneratorDrawer(114                        open = f.generatorOpen,115                        length = f.genLength,116                        upper = f.genUpper, lower = f.genLower, numbers = f.genNumbers, symbols = f.genSymbols,117                        onLength = vm::setGenLength,118                        onUpper = vm::setGenUpper, onLower = vm::setGenLower,119                        onNumbers = vm::setGenNumbers, onSymbols = vm::setGenSymbols,120                        onGenerate = vm::generate,121                    )122                    PasswordHistorySection(123                        history = f.history,124                        expanded = f.showHistory,125                        onToggle = vm::toggleHistory,126                        onRestore = vm::restorePassword,127                        onCopy = vm::copyHistoryPassword,128                    )129                    Field("2FA secret (otpauth:// or base32)", f.totp, vm::setTotp)130                }131                if (f.type == "card") {132                    CardEditFields(133                        cardNumber = f.cardNumber,134                        cardholderName = f.cardholderName,135                        expiry = f.expiry,136                        cvc = f.cvc,137                        showCvc = f.showCvc,138                        network = f.cardNetwork,139                        onCardNumber = vm::setCardNumber,140                        onCardholder = vm::setCardholderName,141                        onExpiry = vm::setExpiry,142                        onCvc = vm::setCvc,143                        onToggleShowCvc = vm::toggleShowCvc,144                    )145                }146                Field("notes", f.notes, vm::setNotes, singleLine = false)147                TagChipEditor(148                    tags = f.tags,149                    allTags = vm.allTags,150                    onAdd = vm::addTag,151                    onRemove = vm::removeTag,152                )153154                f.error?.let {155                    Spacer(Modifier.height(8.dp))156                    Text(it, color = PeachColors.Breach, fontFamily = PeachType.Mono, fontSize = 11.sp)157                }158                Spacer(Modifier.height(40.dp))159                }160            }161        }162    }163}164165@Composable166private fun EntryTypePill(type: String, selected: Boolean, onClick: () -> Unit) {167    val accent = LocalPeachAccent.current168    Box(169        modifier = Modifier170            .clip(RoundedCornerShape(PeachRadius.TypeTab))171            .border(172                1.dp,173                if (selected) accent.copy(alpha = 0.5f) else PeachColors.T3,174                RoundedCornerShape(PeachRadius.TypeTab),175            )176            .background(if (selected) accent.copy(alpha = 0.08f) else Color.Transparent)177            .clickable(onClick = onClick)178            .padding(horizontal = 12.dp, vertical = 5.dp),179    ) {180        Text(181            text = type.uppercase(),182            color = if (selected) accent else PeachColors.T2,183            fontFamily = PeachType.Mono,184            fontSize = 9.sp,185            letterSpacing = 0.08.em,186        )187    }188}189190@Composable191private fun Field(192    label: String,193    value: String,194    onChange: (String) -> Unit,195    singleLine: Boolean = true,196    transformation: VisualTransformation = VisualTransformation.None,197    trailing: (@Composable () -> Unit)? = null,198) {199    val accent = LocalPeachAccent.current200    Column(Modifier.fillMaxWidth().padding(bottom = 14.dp)) {201        Text(label.uppercase(), color = PeachColors.T1, fontFamily = PeachType.Mono, fontSize = 8.sp)202        Spacer(Modifier.height(6.dp))203        Row(verticalAlignment = Alignment.CenterVertically) {204            Box(205                Modifier.weight(1f)206                    .border(1.dp, PeachColors.T3, RoundedCornerShape(10.dp))207                    .padding(horizontal = 12.dp, vertical = 12.dp),208            ) {209                BasicTextField(210                    value = value,211                    onValueChange = onChange,212                    singleLine = singleLine,213                    textStyle = TextStyle(color = PeachColors.T0, fontFamily = PeachType.Mono, fontSize = 13.sp),214                    cursorBrush = SolidColor(accent),215                    visualTransformation = transformation,216                    modifier = Modifier.fillMaxWidth(),217                )218            }219            if (trailing != null) { Spacer(Modifier.width(8.dp)); trailing() }220        }221    }222}223224@Composable225private fun PasswordField(226    value: String,227    show: Boolean,228    onChange: (String) -> Unit,229    onToggleShow: () -> Unit,230    onToggleGenerator: () -> Unit,231) {232    Field(233        label = "password",234        value = value,235        onChange = onChange,236        transformation = if (show) VisualTransformation.None else PasswordVisualTransformation(),237        trailing = {238            Text(if (show) "hide" else "show", color = LocalPeachAccent.current,239                fontFamily = PeachType.Mono, fontSize = 9.sp,240                modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onToggleShow).padding(6.dp))241            Text("⟳", color = LocalPeachAccent.current, fontSize = 16.sp,242                modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onToggleGenerator).padding(6.dp))243        },244    )245}246247@Composable248private fun GeneratorDrawer(249    open: Boolean,250    length: Int,251    upper: Boolean, lower: Boolean, numbers: Boolean, symbols: Boolean,252    onLength: (Int) -> Unit,253    onUpper: (Boolean) -> Unit, onLower: (Boolean) -> Unit,254    onNumbers: (Boolean) -> Unit, onSymbols: (Boolean) -> Unit,255    onGenerate: () -> Unit,256) {257    val accent = LocalPeachAccent.current258    val height by animateDpAsState(259        targetValue = if (open) 188.dp else 0.dp,260        animationSpec = tween(320, easing = PeachMotion.Spring),261        label = "gen-drawer",262    )263    Box(264        Modifier.fillMaxWidth().height(height).clipToBounds()265            .clip(RoundedCornerShape(12.dp)).background(PeachColors.S2),266    ) {267        Column(Modifier.fillMaxWidth().padding(16.dp)) {268            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {269                Text("GENERATOR", color = PeachColors.T1, fontFamily = PeachType.Mono, fontSize = 8.sp)270                Text("length $length", color = accent, fontFamily = PeachType.Mono, fontSize = 9.sp)271            }272            Slider(273                value = length.toFloat(),274                onValueChange = { onLength(it.toInt()) },275                valueRange = 8f..128f,276                colors = SliderDefaults.colors(thumbColor = accent, activeTrackColor = accent,277                    inactiveTrackColor = PeachColors.T3),278            )279            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {280                TogglePill("A-Z", upper, onUpper)281                TogglePill("a-z", lower, onLower)282                TogglePill("0-9", numbers, onNumbers)283                TogglePill("!@#", symbols, onSymbols)284            }285            Spacer(Modifier.height(12.dp))286            Box(287                Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))288                    .border(1.dp, accent.copy(alpha = 0.5f), RoundedCornerShape(10.dp))289                    .background(accent.copy(alpha = 0.10f))290                    .clickable(onClick = onGenerate).padding(vertical = 12.dp),291                contentAlignment = Alignment.Center,292            ) {293                Text("generate", color = accent, fontFamily = PeachType.Mono, fontSize = 12.sp)294            }295        }296    }297    if (open) Spacer(Modifier.height(14.dp))298}299300@Composable301private fun TogglePill(label: String, on: Boolean, onToggle: (Boolean) -> Unit) {302    val accent = LocalPeachAccent.current303    Box(304        Modifier.clip(RoundedCornerShape(PeachRadius.TypeTab))305            .border(1.dp, if (on) accent.copy(alpha = 0.5f) else PeachColors.T3, RoundedCornerShape(PeachRadius.TypeTab))306            .background(if (on) accent.copy(alpha = 0.10f) else Color.Transparent)307            .clickable { onToggle(!on) }308            .padding(horizontal = 10.dp, vertical = 6.dp),309    ) {310        Text(label, color = if (on) accent else PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 9.sp)311    }312}313314/**315 * Past-password history. The toggle is always present (even with no history) so316 * the affordance is discoverable — empty state explains how it fills. Rows are317 * masked until revealed; "use" loads the value back into the editor so the318 * normal save records the swap.319 */320@Composable321private fun PasswordHistorySection(322    history: List<PasswordHistoryItem>,323    expanded: Boolean,324    onToggle: () -> Unit,325    onRestore: (String) -> Unit,326    onCopy: (String) -> Unit,327) {328    val accent = LocalPeachAccent.current329    Column(Modifier.fillMaxWidth().padding(bottom = 14.dp)) {330        val label = if (history.isEmpty()) "↺ history" else "↺ history (${history.size})"331        Text(332            if (expanded) "↺ hide history" else label,333            color = accent.copy(alpha = 0.7f),334            fontFamily = PeachType.Display,335            fontStyle = FontStyle.Italic,336            fontSize = 15.sp,337            modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onToggle).padding(vertical = 4.dp),338        )339        if (expanded) {340            Spacer(Modifier.height(8.dp))341            if (history.isEmpty()) {342                Box(343                    Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))344                        .border(1.dp, accent.copy(alpha = 0.12f), RoundedCornerShape(8.dp))345                        .background(accent.copy(alpha = 0.05f)).padding(10.dp),346                ) {347                    Text(348                        "No earlier passwords yet. When you change this password, the old one is saved here so you can copy or restore it.",349                        color = PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 10.sp,350                    )351                }352            } else {353                Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {354                    history.forEach { item -> HistoryRow(item, onRestore, onCopy) }355                }356            }357        }358    }359}360361@Composable362private fun HistoryRow(363    item: PasswordHistoryItem,364    onRestore: (String) -> Unit,365    onCopy: (String) -> Unit,366) {367    val accent = LocalPeachAccent.current368    var revealed by remember { mutableStateOf(false) }369    Row(370        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))371            .border(1.dp, accent.copy(alpha = 0.12f), RoundedCornerShape(8.dp))372            .background(accent.copy(alpha = 0.06f)).padding(horizontal = 10.dp, vertical = 8.dp),373        verticalAlignment = Alignment.CenterVertically,374        horizontalArrangement = Arrangement.SpaceBetween,375    ) {376        Column(Modifier.weight(1f)) {377            Text(378                if (revealed) item.password else "••••••••••••",379                color = PeachColors.T0, fontFamily = PeachType.Mono, fontSize = 12.sp, maxLines = 1,380            )381            Text(382                timeSince(item.changedAt),383                color = accent.copy(alpha = 0.55f), fontFamily = PeachType.Mono, fontSize = 8.sp,384            )385        }386        Spacer(Modifier.width(6.dp))387        HistoryAction(if (revealed) "hide" else "show") { revealed = !revealed }388        HistoryAction("copy") { onCopy(item.password) }389        HistoryAction("use") { onRestore(item.password) }390    }391}392393@Composable394private fun HistoryAction(label: String, onClick: () -> Unit) {395    Text(396        label, color = LocalPeachAccent.current.copy(alpha = 0.7f),397        fontFamily = PeachType.Mono, fontSize = 9.sp,398        modifier = Modifier.clip(RoundedCornerShape(5.dp)).clickable(onClick = onClick).padding(horizontal = 5.dp, vertical = 3.dp),399    )400}401402/** Coarse "time since" label for the history list. Mirrors the browser helper. */403private fun timeSince(whenMs: Long): String {404    val secs = ((System.currentTimeMillis() - whenMs) / 1000).coerceAtLeast(0)405    if (secs < 60) return "just now"406    val mins = secs / 60407    if (mins < 60) return "${mins}m ago"408    val hours = mins / 60409    if (hours < 24) return "${hours}h ago"410    val days = hours / 24411    if (days < 30) return "${days}d ago"412    val months = days / 30413    if (months < 12) return "${months}mo ago"414    return "${months / 12}y ago"415}