EntryEditScreen.kt

19.0 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.components.CopyButton49import com.peachpasswords.ui.theme.LocalPeachAccent50import com.peachpasswords.ui.theme.PeachColors51import com.peachpasswords.ui.theme.PeachMotion52import com.peachpasswords.ui.theme.PeachRadius53import com.peachpasswords.ui.theme.PeachType54import com.peachpasswords.ui.theme.ShellBackground55import com.peachpasswords.vault.PasswordHistoryItem5657@Composable58fun EntryEditScreen(59    id: String?,60    onBack: () -> Unit,61    vm: EntryEditViewModel = hiltViewModel(),62) {63    val f by vm.form.collectAsState()64    val usernameSuggestions by vm.usernameSuggestions.collectAsState()65    val accent = LocalPeachAccent.current6667    ShellBackground {68        Column(Modifier.fillMaxSize().statusBarsPadding()) {69            Row(70                Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 18.dp),71                verticalAlignment = Alignment.CenterVertically,72                horizontalArrangement = Arrangement.SpaceBetween,73            ) {74                Text("cancel", color = PeachColors.T1, fontFamily = PeachType.Mono, fontSize = 12.sp,75                    modifier = Modifier.clip(RoundedCornerShape(8.dp)).clickable(onClick = onBack).padding(8.dp))76                Text(if (vm.isNew) "new entry" else "edit", color = PeachColors.T1,77                    fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 16.sp)78                Text("save", color = accent, fontFamily = PeachType.Mono, fontSize = 13.sp,79                    modifier = Modifier.clip(RoundedCornerShape(8.dp)).clickable { vm.save(onBack) }.padding(8.dp))80            }8182            Box(Modifier.fillMaxSize()) {83                // Ghost PeachScript watermark behind the form (matches the detail hero).84                if (f.title.isNotBlank()) {85                    Text(86                        text = f.title.first().uppercase(),87                        style = TextStyle(fontFamily = PeachType.Script, fontSize = 140.sp),88                        color = PeachColors.T0.copy(alpha = 0.03f),89                        modifier = Modifier.align(Alignment.TopEnd).offset(x = (-16).dp, y = 8.dp),90                    )91                }92                Column(93                    Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 22.dp),94                ) {95                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {96                    listOf("login", "note", "card").forEach { t ->97                        EntryTypePill(t, f.type == t) { vm.setType(t) }98                    }99                }100                Spacer(Modifier.height(18.dp))101102                Field("title", f.title, vm::setTitle)103                if (f.type == "login") {104                    Field("url", f.url, vm::setUrl)105                    AdditionalUrlsEditor(106                        urls = f.additionalUrls,107                        onChange = vm::setAdditionalUrl,108                        onAdd = vm::addAdditionalUrl,109                        onRemove = vm::removeAdditionalUrl,110                    )111                    IdentitySuggestField("username", f.username, usernameSuggestions, vm::setUsername)112                    IdentitySuggestField("email", f.email, usernameSuggestions, vm::setEmail)113                    PasswordField(114                        value = f.password,115                        show = f.showPassword,116                        onChange = vm::setPassword,117                        onToggleShow = vm::toggleShowPassword,118                        onToggleGenerator = vm::toggleGenerator,119                    )120                    GeneratorDrawer(121                        open = f.generatorOpen,122                        length = f.genLength,123                        upper = f.genUpper, lower = f.genLower, numbers = f.genNumbers, symbols = f.genSymbols,124                        password = f.password,125                        copied = f.genCopied,126                        onLength = vm::setGenLength,127                        onUpper = vm::setGenUpper, onLower = vm::setGenLower,128                        onNumbers = vm::setGenNumbers, onSymbols = vm::setGenSymbols,129                        onGenerate = vm::generate,130                        onCopy = vm::copyGenerated,131                    )132                    PasswordHistorySection(133                        history = f.history,134                        expanded = f.showHistory,135                        onToggle = vm::toggleHistory,136                        onRestore = vm::restorePassword,137                        onCopy = vm::copyHistoryPassword,138                    )139                    Field("2FA secret (otpauth:// or base32)", f.totp, vm::setTotp)140                }141                if (f.type == "card") {142                    CardEditFields(143                        cardNumber = f.cardNumber,144                        cardholderName = f.cardholderName,145                        expiry = f.expiry,146                        cvc = f.cvc,147                        showCvc = f.showCvc,148                        network = f.cardNetwork,149                        onCardNumber = vm::setCardNumber,150                        onCardholder = vm::setCardholderName,151                        onExpiry = vm::setExpiry,152                        onCvc = vm::setCvc,153                        onToggleShowCvc = vm::toggleShowCvc,154                    )155                }156                Field("notes", f.notes, vm::setNotes, singleLine = false)157                TagChipEditor(158                    tags = f.tags,159                    allTags = vm.allTags,160                    onAdd = vm::addTag,161                    onRemove = vm::removeTag,162                )163164                f.error?.let {165                    Spacer(Modifier.height(8.dp))166                    Text(it, color = PeachColors.Breach, fontFamily = PeachType.Mono, fontSize = 11.sp)167                }168                Spacer(Modifier.height(40.dp))169                }170            }171        }172    }173}174175@Composable176private fun EntryTypePill(type: String, selected: Boolean, onClick: () -> Unit) {177    val accent = LocalPeachAccent.current178    Box(179        modifier = Modifier180            .clip(RoundedCornerShape(PeachRadius.TypeTab))181            .border(182                1.dp,183                if (selected) accent.copy(alpha = 0.5f) else PeachColors.T3,184                RoundedCornerShape(PeachRadius.TypeTab),185            )186            .background(if (selected) accent.copy(alpha = 0.08f) else Color.Transparent)187            .clickable(onClick = onClick)188            .padding(horizontal = 12.dp, vertical = 5.dp),189    ) {190        Text(191            text = type.uppercase(),192            color = if (selected) accent else PeachColors.T2,193            fontFamily = PeachType.Mono,194            fontSize = 9.sp,195            letterSpacing = 0.08.em,196        )197    }198}199200@Composable201private fun Field(202    label: String,203    value: String,204    onChange: (String) -> Unit,205    singleLine: Boolean = true,206    transformation: VisualTransformation = VisualTransformation.None,207    trailing: (@Composable () -> Unit)? = null,208) {209    val accent = LocalPeachAccent.current210    Column(Modifier.fillMaxWidth().padding(bottom = 14.dp)) {211        Text(label.uppercase(), color = PeachColors.T1, fontFamily = PeachType.Mono, fontSize = 8.sp)212        Spacer(Modifier.height(6.dp))213        Row(verticalAlignment = Alignment.CenterVertically) {214            Box(215                Modifier.weight(1f)216                    .border(1.dp, PeachColors.T3, RoundedCornerShape(10.dp))217                    .padding(horizontal = 12.dp, vertical = 12.dp),218            ) {219                BasicTextField(220                    value = value,221                    onValueChange = onChange,222                    singleLine = singleLine,223                    textStyle = TextStyle(color = PeachColors.T0, fontFamily = PeachType.Mono, fontSize = 13.sp),224                    cursorBrush = SolidColor(accent),225                    visualTransformation = transformation,226                    modifier = Modifier.fillMaxWidth(),227                )228            }229            if (trailing != null) { Spacer(Modifier.width(8.dp)); trailing() }230        }231    }232}233234@Composable235private fun PasswordField(236    value: String,237    show: Boolean,238    onChange: (String) -> Unit,239    onToggleShow: () -> Unit,240    onToggleGenerator: () -> Unit,241) {242    Field(243        label = "password",244        value = value,245        onChange = onChange,246        transformation = if (show) VisualTransformation.None else PasswordVisualTransformation(),247        trailing = {248            Text(if (show) "hide" else "show", color = LocalPeachAccent.current,249                fontFamily = PeachType.Mono, fontSize = 9.sp,250                modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onToggleShow).padding(6.dp))251            Text("⟳", color = LocalPeachAccent.current, fontSize = 16.sp,252                modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onToggleGenerator).padding(6.dp))253        },254    )255}256257@Composable258private fun GeneratorDrawer(259    open: Boolean,260    length: Int,261    upper: Boolean, lower: Boolean, numbers: Boolean, symbols: Boolean,262    password: String,263    copied: Boolean,264    onLength: (Int) -> Unit,265    onUpper: (Boolean) -> Unit, onLower: (Boolean) -> Unit,266    onNumbers: (Boolean) -> Unit, onSymbols: (Boolean) -> Unit,267    onGenerate: () -> Unit,268    onCopy: () -> Unit,269) {270    val height by animateDpAsState(271        targetValue = if (open) 234.dp else 0.dp,272        animationSpec = tween(320, easing = PeachMotion.Spring),273        label = "gen-drawer",274    )275    Box(276        Modifier.fillMaxWidth().height(height).clipToBounds()277            .clip(RoundedCornerShape(12.dp)).background(PeachColors.S2),278    ) {279        GeneratorBody(280            length = length,281            upper = upper, lower = lower, numbers = numbers, symbols = symbols,282            password = password, copied = copied,283            onLength = onLength,284            onUpper = onUpper, onLower = onLower, onNumbers = onNumbers, onSymbols = onSymbols,285            onGenerate = onGenerate, onCopy = onCopy,286        )287    }288    if (open) Spacer(Modifier.height(14.dp))289}290291/**292 * Shared generator body — used by the inline drawer here and the detail293 * ModalBottomSheet (D4). Stateless; the generate row carries the [Copy] drain.294 */295@Composable296internal fun GeneratorBody(297    length: Int,298    upper: Boolean, lower: Boolean, numbers: Boolean, symbols: Boolean,299    password: String,300    copied: Boolean,301    onLength: (Int) -> Unit,302    onUpper: (Boolean) -> Unit, onLower: (Boolean) -> Unit,303    onNumbers: (Boolean) -> Unit, onSymbols: (Boolean) -> Unit,304    onGenerate: () -> Unit,305    onCopy: () -> Unit,306) {307    val accent = LocalPeachAccent.current308    Column(Modifier.fillMaxWidth().padding(16.dp)) {309        Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {310            Text("GENERATOR", color = PeachColors.T1, fontFamily = PeachType.Mono, fontSize = 8.sp)311            Text("length $length", color = accent, fontFamily = PeachType.Mono, fontSize = 9.sp)312        }313        Slider(314            value = length.toFloat(),315            onValueChange = { onLength(it.toInt()) },316            valueRange = 8f..128f,317            colors = SliderDefaults.colors(318                thumbColor = accent, activeTrackColor = accent, inactiveTrackColor = PeachColors.T3,319            ),320        )321        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {322            TogglePill("A-Z", upper, onUpper)323            TogglePill("a-z", lower, onLower)324            TogglePill("0-9", numbers, onNumbers)325            TogglePill("!@#", symbols, onSymbols)326        }327        Spacer(Modifier.height(12.dp))328        Row(verticalAlignment = Alignment.CenterVertically) {329            Box(330                Modifier.weight(1f).clip(RoundedCornerShape(10.dp))331                    .border(1.dp, accent.copy(alpha = 0.5f), RoundedCornerShape(10.dp))332                    .background(accent.copy(alpha = 0.10f))333                    .clickable(onClick = onGenerate).padding(vertical = 12.dp),334                contentAlignment = Alignment.Center,335            ) {336                Text("generate", color = accent, fontFamily = PeachType.Mono, fontSize = 12.sp)337            }338            Spacer(Modifier.width(8.dp))339            CopyButton(copied = copied, onCopy = { if (password.isNotEmpty()) onCopy() })340        }341    }342}343344@Composable345private fun TogglePill(label: String, on: Boolean, onToggle: (Boolean) -> Unit) {346    val accent = LocalPeachAccent.current347    Box(348        Modifier.clip(RoundedCornerShape(PeachRadius.TypeTab))349            .border(1.dp, if (on) accent.copy(alpha = 0.5f) else PeachColors.T3, RoundedCornerShape(PeachRadius.TypeTab))350            .background(if (on) accent.copy(alpha = 0.10f) else Color.Transparent)351            .clickable { onToggle(!on) }352            .padding(horizontal = 10.dp, vertical = 6.dp),353    ) {354        Text(label, color = if (on) accent else PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 9.sp)355    }356}357358/**359 * Past-password history. The toggle is always present (even with no history) so360 * the affordance is discoverable — empty state explains how it fills. Rows are361 * masked until revealed; "use" loads the value back into the editor so the362 * normal save records the swap.363 */364@Composable365private fun PasswordHistorySection(366    history: List<PasswordHistoryItem>,367    expanded: Boolean,368    onToggle: () -> Unit,369    onRestore: (String) -> Unit,370    onCopy: (String) -> Unit,371) {372    val accent = LocalPeachAccent.current373    Column(Modifier.fillMaxWidth().padding(bottom = 14.dp)) {374        val label = if (history.isEmpty()) "↺ history" else "↺ history (${history.size})"375        Text(376            if (expanded) "↺ hide history" else label,377            color = accent.copy(alpha = 0.7f),378            fontFamily = PeachType.Display,379            fontStyle = FontStyle.Italic,380            fontSize = 15.sp,381            modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onToggle).padding(vertical = 4.dp),382        )383        if (expanded) {384            Spacer(Modifier.height(8.dp))385            if (history.isEmpty()) {386                Box(387                    Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))388                        .border(1.dp, accent.copy(alpha = 0.12f), RoundedCornerShape(8.dp))389                        .background(accent.copy(alpha = 0.05f)).padding(10.dp),390                ) {391                    Text(392                        "No earlier passwords yet. When you change this password, the old one is saved here so you can copy or restore it.",393                        color = PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 10.sp,394                    )395                }396            } else {397                Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {398                    history.forEach { item -> HistoryRow(item, onRestore, onCopy) }399                }400            }401        }402    }403}404405@Composable406private fun HistoryRow(407    item: PasswordHistoryItem,408    onRestore: (String) -> Unit,409    onCopy: (String) -> Unit,410) {411    val accent = LocalPeachAccent.current412    var revealed by remember { mutableStateOf(false) }413    Row(414        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))415            .border(1.dp, accent.copy(alpha = 0.12f), RoundedCornerShape(8.dp))416            .background(accent.copy(alpha = 0.06f)).padding(horizontal = 10.dp, vertical = 8.dp),417        verticalAlignment = Alignment.CenterVertically,418        horizontalArrangement = Arrangement.SpaceBetween,419    ) {420        Column(Modifier.weight(1f)) {421            Text(422                if (revealed) item.password else "••••••••••••",423                color = PeachColors.T0, fontFamily = PeachType.Mono, fontSize = 12.sp, maxLines = 1,424            )425            Text(426                timeSince(item.changedAt),427                color = accent.copy(alpha = 0.55f), fontFamily = PeachType.Mono, fontSize = 8.sp,428            )429        }430        Spacer(Modifier.width(6.dp))431        HistoryAction(if (revealed) "hide" else "show") { revealed = !revealed }432        HistoryAction("copy") { onCopy(item.password) }433        HistoryAction("use") { onRestore(item.password) }434    }435}436437@Composable438private fun HistoryAction(label: String, onClick: () -> Unit) {439    Text(440        label, color = LocalPeachAccent.current.copy(alpha = 0.7f),441        fontFamily = PeachType.Mono, fontSize = 9.sp,442        modifier = Modifier.clip(RoundedCornerShape(5.dp)).clickable(onClick = onClick).padding(horizontal = 5.dp, vertical = 3.dp),443    )444}445446/** Coarse "time since" label for the history list. Mirrors the browser helper. */447private fun timeSince(whenMs: Long): String {448    val secs = ((System.currentTimeMillis() - whenMs) / 1000).coerceAtLeast(0)449    if (secs < 60) return "just now"450    val mins = secs / 60451    if (mins < 60) return "${mins}m ago"452    val hours = mins / 60453    if (hours < 24) return "${hours}h ago"454    val days = hours / 24455    if (days < 30) return "${days}d ago"456    val months = days / 30457    if (months < 12) return "${months}mo ago"458    return "${months / 12}y ago"459}