EntryEditScreen.kt

20.2 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.verticalScroll23import androidx.compose.material3.Slider24import androidx.compose.material3.SliderDefaults25import androidx.compose.material3.Text26import androidx.compose.runtime.Composable27import androidx.compose.runtime.getValue28import androidx.compose.runtime.mutableStateOf29import androidx.compose.runtime.remember30import androidx.compose.runtime.setValue31import androidx.compose.ui.Alignment32import androidx.compose.ui.Modifier33import androidx.compose.ui.draw.clip34import androidx.compose.ui.draw.clipToBounds35import androidx.compose.ui.graphics.Color36import androidx.compose.ui.text.TextStyle37import androidx.compose.ui.text.font.FontStyle38import androidx.compose.ui.text.font.FontWeight39import androidx.compose.ui.text.input.PasswordVisualTransformation40import androidx.compose.ui.text.input.VisualTransformation41import androidx.compose.ui.text.style.TextOverflow42import androidx.compose.ui.unit.dp43import androidx.compose.ui.unit.em44import androidx.compose.ui.unit.sp45import androidx.compose.runtime.collectAsState46import androidx.hilt.navigation.compose.hiltViewModel47import com.peachpasswords.ui.components.CopyButton48import 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.ShellBackground5455@Composable56fun EntryEditScreen(57    id: String?,58    onBack: () -> Unit,59    onOpenNote: (String) -> Unit = {},60    vm: EntryEditViewModel = hiltViewModel(),61) {62    val f by vm.form.collectAsState()63    val usernameSuggestions by vm.usernameSuggestions.collectAsState()64    val emailSuggestions by vm.emailSuggestions.collectAsState()65    val accent = LocalPeachAccent.current6667    // Ghost watermark fades in (0 → 0.03α over 300ms) once the title has any text.68    val watermarkAlpha by androidx.compose.animation.core.animateFloatAsState(69        targetValue = editGhostWatermarkTarget(f.title),70        animationSpec = tween(300),71        label = "edit-watermark",72    )7374    ShellBackground {75        Column(Modifier.fillMaxSize().statusBarsPadding()) {76            Box(Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 18.dp)) {77                val canSave = canSaveEditForm(f)78                Text("cancel", color = peachColors.T2, fontFamily = PeachType.Mono, fontSize = 11.sp,79                    modifier = Modifier.align(Alignment.CenterStart)80                        .clip(RoundedCornerShape(8.dp)).clickable(onClick = onBack).padding(8.dp))81                Text(editTitleBarLabel(vm.isNew, f.type), color = peachColors.T1,82                    fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 18.sp,83                    modifier = Modifier.align(Alignment.Center))84                Text(entryEditPrimaryActionLabel(vm.isNew, f.saving), color = if (canSave && !f.saving) accent else peachColors.T2, fontFamily = PeachType.Mono, fontSize = 11.sp,85                    modifier = Modifier.align(Alignment.CenterEnd)86                        .clip(RoundedCornerShape(8.dp)).clickable(enabled = canSave && !f.saving) { vm.save(onBack) }.padding(8.dp))87            }8889            Box(Modifier.fillMaxSize().clipToBounds()) {90                // Ghost PeachScript watermark behind the form (matches the detail hero):91                // the full title, fading in as the user types.92                if (watermarkAlpha > 0f) {93                    Text(94                        text = ghostWatermarkText(f.title),95                        style = TextStyle(fontFamily = PeachType.Script, fontSize = 140.sp),96                        color = peachColors.T0.copy(alpha = watermarkAlpha),97                        maxLines = 1,98                        softWrap = false,99                        overflow = androidx.compose.ui.text.style.TextOverflow.Clip,100                        modifier = Modifier.align(Alignment.TopEnd).offset(x = (-16).dp, y = 8.dp),101                    )102                }103                Column(104                    Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 22.dp),105                ) {106                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {107                    listOf("login", "note", "card").forEach { t ->108                        EntryTypePill(t, f.type == t) {109                            // A brand-new note skips the form entirely and drops straight110                            // into the full-screen notes editor (brief Fix 6 item 7).111                            if (shouldOpenNotesMode(vm.isNew, t)) vm.createNoteAndOpen(onOpenNote)112                            else vm.setType(t)113                        }114                    }115                }116                Spacer(Modifier.height(18.dp))117118                Field("title", f.title, vm::setTitle)119                if (f.type == "login") {120                    Field("url", f.url, vm::setUrl)121                    AdditionalUrlsEditor(122                        urls = f.additionalUrls,123                        onChange = vm::setAdditionalUrl,124                        onAdd = vm::addAdditionalUrl,125                        onRemove = vm::removeAdditionalUrl,126                    )127                    IdentitySuggestField("username", f.username, usernameSuggestions, vm::setUsername)128                    IdentitySuggestField("email", f.email, emailSuggestions, vm::setEmail)129                    PasswordField(130                        value = f.password,131                        show = f.showPassword,132                        generatorOpen = f.generatorOpen,133                        onChange = vm::setPassword,134                        onToggleShow = vm::toggleShowPassword,135                        onToggleGenerator = vm::toggleGenerator,136                    )137                    GeneratorDrawer(138                        open = f.generatorOpen,139                        length = f.genLength,140                        upper = f.genUpper, lower = f.genLower, numbers = f.genNumbers, symbols = f.genSymbols,141                        password = f.password,142                        copied = f.genCopied,143                        onLength = vm::setGenLength,144                        onUpper = vm::setGenUpper, onLower = vm::setGenLower,145                        onNumbers = vm::setGenNumbers, onSymbols = vm::setGenSymbols,146                        onGenerate = vm::generate,147                        onCopy = vm::copyGenerated,148                        onUse = vm::useGeneratedPassword,149                    )150                    PasswordHistorySection(151                        history = f.history,152                        expanded = f.showHistory,153                        onToggle = vm::toggleHistory,154                        onRestore = vm::restorePassword,155                        onCopy = vm::copyHistoryPassword,156                    )157                    if (shouldShowLoginTotp(f.type, f.showTotp, f.totp)) {158                        Field("2FA secret (otpauth:// or base32)", f.totp, vm::setTotp)159                    }160                }161                if (f.type == "card") {162                    CardEditFields(163                        cardNumber = f.cardNumber,164                        cardholderName = f.cardholderName,165                        expiry = f.expiry,166                        cvc = f.cvc,167                        showCvc = f.showCvc,168                        network = f.cardNetwork,169                        onCardNumber = vm::setCardNumber,170                        onCardholder = vm::setCardholderName,171                        onExpiry = vm::setExpiry,172                        onCvc = vm::setCvc,173                        onToggleShowCvc = vm::toggleShowCvc,174                    )175                }176                if (f.type == "note" || shouldShowLoginNotes(f.type, f.showNotes, f.notes)) {177                    Field("notes", f.notes, vm::setNotes, singleLine = false)178                }179                if (f.type == "login") {180                    OptionalLoginAddLinks(181                        showTotpLink = shouldShowAddTotpLink(f.type, f.showTotp, f.totp),182                        showNotesLink = shouldShowAddNotesLink(f.type, f.showNotes, f.notes),183                        onAddTotp = vm::revealTotp,184                        onAddNotes = vm::revealNotes,185                    )186                }187                TagChipEditor(188                    tags = f.tags,189                    allTags = vm.allTags,190                    onAdd = vm::addTag,191                    onRemove = vm::removeTag,192                )193194                f.error?.let {195                    Spacer(Modifier.height(8.dp))196                    Text(it, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 11.sp)197                }198                Spacer(Modifier.height(40.dp))199                }200            }201        }202    }203}204205@Composable206private fun EntryTypePill(type: String, selected: Boolean, onClick: () -> Unit) {207    val accent = LocalPeachAccent.current208    Box(209        modifier = Modifier210            .clip(RoundedCornerShape(PeachRadius.TypeTab))211            .border(212                1.dp,213                if (selected) accent.copy(alpha = 0.5f) else peachColors.T3,214                RoundedCornerShape(PeachRadius.TypeTab),215            )216            .background(if (selected) accent.copy(alpha = 0.08f) else Color.Transparent)217            .clickable(onClick = onClick)218            .padding(horizontal = 12.dp, vertical = 5.dp),219    ) {220        Text(221            text = type.uppercase(),222            color = if (selected) accent else peachColors.T2,223            fontFamily = PeachType.Mono,224            fontSize = 9.sp,225            letterSpacing = 0.08.em,226        )227    }228}229230/** Centered title-bar label: "new entry" / "new note" / "new card", or "edit". */231internal fun editTitleBarLabel(isNew: Boolean, type: String): String = when {232    !isNew -> "edit"233    type == "note" -> "new note"234    type == "card" -> "new card"235    else -> "new entry"236}237238internal fun entryEditPrimaryActionLabel(isNew: Boolean, saving: Boolean): String = when {239    saving -> "saving..."240    isNew -> "create"241    else -> "save"242}243244internal fun canSaveEditForm(form: EditForm): Boolean {245    if (form.title.isBlank()) return false246    if (form.type == "card" && (form.cardholderName.isBlank() || form.cardNumber.isBlank())) return false247    return true248}249250/** A brand-new note opens the full-screen notes editor instead of the form. */251internal fun shouldOpenNotesMode(isNew: Boolean, type: String): Boolean = isNew && type == "note"252253/** Target alpha for the edit-screen ghost watermark — visible only once a title exists. */254internal fun editGhostWatermarkTarget(title: String): Float = if (title.isNotBlank()) 0.03f else 0f255256internal fun shouldShowLoginTotp(type: String, revealed: Boolean, totp: String): Boolean =257    type == "login" && (revealed || totp.isNotBlank())258259internal fun shouldShowLoginNotes(type: String, revealed: Boolean, notes: String): Boolean =260    type == "login" && (revealed || notes.isNotBlank())261262internal fun shouldShowAddTotpLink(type: String, revealed: Boolean, totp: String): Boolean =263    type == "login" && !shouldShowLoginTotp(type, revealed, totp)264265internal fun shouldShowAddNotesLink(type: String, revealed: Boolean, notes: String): Boolean =266    type == "login" && !shouldShowLoginNotes(type, revealed, notes)267268@Composable269private fun OptionalLoginAddLinks(270    showTotpLink: Boolean,271    showNotesLink: Boolean,272    onAddTotp: () -> Unit,273    onAddNotes: () -> Unit,274) {275    if (!showTotpLink && !showNotesLink) return276    Row(277        Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 8.dp),278        horizontalArrangement = Arrangement.spacedBy(14.dp),279    ) {280        if (showTotpLink) AddFieldLink("+ add 2FA", onAddTotp)281        if (showNotesLink) AddFieldLink("+ add notes", onAddNotes)282    }283}284285@Composable286private fun AddFieldLink(label: String, onClick: () -> Unit) {287    Text(288        label,289        color = LocalPeachAccent.current,290        fontFamily = PeachType.Mono,291        fontSize = 11.sp,292        modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onClick).padding(vertical = 6.dp),293    )294}295296@Composable297private fun Field(298    label: String,299    value: String,300    onChange: (String) -> Unit,301    singleLine: Boolean = true,302    transformation: VisualTransformation = VisualTransformation.None,303    trailing: (@Composable () -> Unit)? = null,304) {305    PeachField(306        label = label,307        value = value,308        onChange = onChange,309        singleLine = singleLine,310        mono = true,311        visualTransformation = transformation,312        trailing = trailing,313    )314}315316@Composable317private fun PasswordField(318    value: String,319    show: Boolean,320    generatorOpen: Boolean,321    onChange: (String) -> Unit,322    onToggleShow: () -> Unit,323    onToggleGenerator: () -> Unit,324) {325    Field(326        label = "password",327        value = value,328        onChange = onChange,329        transformation = if (show) VisualTransformation.None else PasswordVisualTransformation(),330        trailing = {331            Text(if (show) "hide" else "show", color = LocalPeachAccent.current,332                fontFamily = PeachType.Mono, fontSize = 9.sp,333                modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onToggleShow).padding(6.dp))334            Text(generatorToggleLabel(generatorOpen), color = LocalPeachAccent.current,335                fontFamily = PeachType.Mono, fontSize = 9.sp,336                modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onToggleGenerator).padding(6.dp))337        },338    )339}340341internal fun generatorToggleLabel(open: Boolean): String = if (open) "hide generator" else "generate"342343@Composable344private fun GeneratorDrawer(345    open: Boolean,346    length: Int,347    upper: Boolean, lower: Boolean, numbers: Boolean, symbols: Boolean,348    password: String,349    copied: Boolean,350    onLength: (Int) -> Unit,351    onUpper: (Boolean) -> Unit, onLower: (Boolean) -> Unit,352    onNumbers: (Boolean) -> Unit, onSymbols: (Boolean) -> Unit,353    onGenerate: () -> Unit,354    onCopy: () -> Unit,355    onUse: () -> Unit,356) {357    val height by animateDpAsState(358        targetValue = if (open) 326.dp else 0.dp,359        animationSpec = tween(320, easing = PeachMotion.Spring),360        label = "gen-drawer",361    )362    Box(363        Modifier.fillMaxWidth().height(height).clipToBounds()364            .clip(RoundedCornerShape(12.dp)).background(peachColors.S2),365    ) {366        GeneratorBody(367            length = length,368            upper = upper, lower = lower, numbers = numbers, symbols = symbols,369            password = password, copied = copied,370            onLength = onLength,371            onUpper = onUpper, onLower = onLower, onNumbers = onNumbers, onSymbols = onSymbols,372            onGenerate = onGenerate, onCopy = onCopy,373            showOutput = true,374            onUse = onUse,375        )376    }377    if (open) Spacer(Modifier.height(14.dp))378}379380/**381 * Shared generator body — used by the inline drawer here and the detail382 * ModalBottomSheet (D4). Stateless; the generate row carries the [Copy] drain.383 */384@Composable385internal fun GeneratorBody(386    length: Int,387    upper: Boolean, lower: Boolean, numbers: Boolean, symbols: Boolean,388    password: String,389    copied: Boolean,390    onLength: (Int) -> Unit,391    onUpper: (Boolean) -> Unit, onLower: (Boolean) -> Unit,392    onNumbers: (Boolean) -> Unit, onSymbols: (Boolean) -> Unit,393    onGenerate: () -> Unit,394    onCopy: () -> Unit,395    showOutput: Boolean = false,396    onUse: (() -> Unit)? = null,397) {398    val accent = LocalPeachAccent.current399    Column(Modifier.fillMaxWidth().padding(16.dp)) {400        if (showOutput) {401            Box(402                Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))403                    .border(1.dp, accent.copy(alpha = 0.45f), RoundedCornerShape(10.dp))404                    .background(accent.copy(alpha = 0.08f))405                    .padding(horizontal = 12.dp, vertical = 10.dp),406            ) {407                Text(408                    text = password.ifEmpty { "tap generate" },409                    color = if (password.isEmpty()) peachColors.T2 else peachColors.T0,410                    fontFamily = PeachType.Mono,411                    fontSize = 11.sp,412                    maxLines = 2,413                    overflow = TextOverflow.Ellipsis,414                )415            }416            Spacer(Modifier.height(10.dp))417        }418        Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {419            Text("GENERATOR", color = peachColors.T1, fontFamily = PeachType.Mono, fontSize = 8.sp)420            Text("length $length", color = accent, fontFamily = PeachType.Mono, fontSize = 9.sp)421        }422        Slider(423            value = length.toFloat(),424            onValueChange = { onLength(it.toInt()) },425            valueRange = 8f..128f,426            colors = SliderDefaults.colors(427                thumbColor = accent, activeTrackColor = accent, inactiveTrackColor = peachColors.T3,428            ),429        )430        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {431            TogglePill("A-Z", upper, onUpper)432            TogglePill("a-z", lower, onLower)433            TogglePill("0-9", numbers, onNumbers)434            TogglePill("!@#", symbols, onSymbols)435        }436        Spacer(Modifier.height(12.dp))437        Row(verticalAlignment = Alignment.CenterVertically) {438            Box(439                Modifier.weight(1f).clip(RoundedCornerShape(10.dp))440                    .border(1.dp, accent.copy(alpha = 0.5f), RoundedCornerShape(10.dp))441                    .background(accent.copy(alpha = 0.10f))442                    .clickable(onClick = onGenerate).padding(vertical = 12.dp),443                contentAlignment = Alignment.Center,444            ) {445                Text(if (password.isEmpty()) "generate" else "regenerate", color = accent, fontFamily = PeachType.Mono, fontSize = 12.sp)446            }447            Spacer(Modifier.width(8.dp))448            CopyButton(copied = copied, onCopy = { if (password.isNotEmpty()) onCopy() })449        }450        onUse?.let {451            Spacer(Modifier.height(10.dp))452            Box(453                Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))454                    .border(1.dp, accent.copy(alpha = 0.5f), RoundedCornerShape(10.dp))455                    .background(accent.copy(alpha = 0.14f))456                    .clickable(enabled = password.isNotEmpty(), onClick = it)457                    .padding(vertical = 12.dp),458                contentAlignment = Alignment.Center,459            ) {460                Text("use", color = if (password.isEmpty()) accent.copy(alpha = 0.45f) else accent, fontFamily = PeachType.Mono, fontSize = 12.sp)461            }462        }463    }464}465466@Composable467private fun TogglePill(label: String, on: Boolean, onToggle: (Boolean) -> Unit) {468    val accent = LocalPeachAccent.current469    Box(470        Modifier.clip(RoundedCornerShape(PeachRadius.TypeTab))471            .border(1.dp, if (on) accent.copy(alpha = 0.5f) else peachColors.T3, RoundedCornerShape(PeachRadius.TypeTab))472            .background(if (on) accent.copy(alpha = 0.10f) else Color.Transparent)473            .clickable { onToggle(!on) }474            .padding(horizontal = 10.dp, vertical = 6.dp),475    ) {476        Text(label, color = if (on) accent else peachColors.T2, fontFamily = PeachType.Mono, fontSize = 9.sp)477    }478}479480// PasswordHistorySection / HistoryRow / HistoryAction / timeSince were extracted481// to ui/vault/PasswordHistorySection.kt (D7) so EntryDetailScreen can reuse them.