Modern Apps git

← Modern-Apps.git

contacts: SIM fields, flag space, note IME gap, account memory (#795, #796, #522, #748)

Commit
d0a261bd1ed2eefbe7f3e4a4d127efe21bf35eea
Author
vayun-mathur <[email protected]>
When
2026-10-13 22:09 UTC (1 month ago)
Parents
ad28315

Diff

contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.ktindex 6bb272beba..bf55c71674 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt@@ -28,6 +28,14 @@ data class SimContact(  const val SIM_ACCOUNT_TYPE = "com.vayunmathur.contacts.sim" +/**+ * SIM ADN rows store a single name, a single number, and a single email address.+ * The add/edit form therefore offers exactly one phone field and one email field+ * for SIM accounts: no type selectors and no add-more buttons.+ */+const val SIM_MAX_PHONE_NUMBERS = 1+const val SIM_MAX_EMAILS = 1+ /** Account type for the app's on-device local accounts (renamable/deletable by the user). */ const val LOCAL_ACCOUNT_TYPE = "com.vayunmathur.contacts.local" 
contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactDetailGroups.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactDetailGroups.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactDetailGroups.ktindex c3fa9e643d..1e2cf92aed 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactDetailGroups.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactDetailGroups.kt@@ -1,9 +1,18 @@ package com.vayunmathur.contacts.ui +import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.unit.dp import com.google.i18n.phonenumbers.PhoneNumberUtil import com.vayunmathur.contacts.R import com.vayunmathur.contacts.data.Address@@ -13,11 +22,14 @@ import com.vayunmathur.contacts.data.CDKStructuredPostal import com.vayunmathur.contacts.data.ContactDetail import com.vayunmathur.contacts.data.Email import com.vayunmathur.contacts.data.PhoneNumber+import com.vayunmathur.contacts.data.SIM_MAX_EMAILS+import com.vayunmathur.contacts.data.SIM_MAX_PHONE_NUMBERS import com.vayunmathur.contacts.util.ContactViewModel import com.vayunmathur.library.ui.FormDetailGroup import com.vayunmathur.library.ui.IconCall import com.vayunmathur.library.ui.IconLocationOn import com.vayunmathur.library.ui.IconMail+import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.ui.Text @@ -26,6 +38,9 @@ import com.vayunmathur.library.ui.Text  *  * A contact always offers a mobile number and a home email, even when blank, so there is  * always somewhere obvious to put the two values almost every contact has.+ *+ * SIM accounts store only a single name, number, and email, so they get one plain+ * phone field and one plain email field with no type selectors or add-more buttons.  */ @Composable fun EditContactDetailGroups(@@ -35,6 +50,30 @@ fun EditContactDetailGroups(     onUpdate: (ContactViewModel.ContactDraft) -> Unit,     isSimAccount: Boolean = false, ) {+    // The flag slot reserves leading space even when empty, so only offer it once at+    // least one number resolves to a country; otherwise local/empty fields gain a gap.+    // Hoisted above the SIM early-return so remember stays unconditional.+    val showCountryFlags = remember(draft.phoneNumbers) {+        draft.phoneNumbers.any { getCountryFlagEmoji(it.value).isNotBlank() }+    }+    if (isSimAccount) {+        // A SIM stores one number and one email; drop extras that arrived with a+        // draft seeded for a non-SIM account (e.g. account switched mid-edit).+        LaunchedEffect(draft.phoneNumbers.size, draft.emails.size) {+            if (draft.phoneNumbers.size > SIM_MAX_PHONE_NUMBERS ||+                draft.emails.size > SIM_MAX_EMAILS+            ) {+                onUpdate(+                    draft.copy(+                        phoneNumbers = draft.phoneNumbers.take(SIM_MAX_PHONE_NUMBERS),+                        emails = draft.emails.take(SIM_MAX_EMAILS),+                    )+                )+            }+        }+        SimContactFields(draft, onUpdate)+        return+    }     val phoneCtx = LocalContext.current     FormDetailGroup(         items = draft.phoneNumbers,@@ -55,7 +94,16 @@ fun EditContactDetailGroups(         onLabelChange = { idx, v -> onUpdate(draft.copy(phoneNumbers = draft.phoneNumbers.toMutableList().also { l -> l[idx] = l[idx].withLabel(v) })) },         customLabelText = stringResource(R.string.custom_label),         customPlaceholder = stringResource(R.string.enter_custom_label),-        leadingIcon = { item -> Text(getCountryFlagEmoji(item.value)) },+        leadingIcon = if (showCountryFlags) {+            { item ->+                val flag = remember(item.value) { getCountryFlagEmoji(item.value) }+                if (flag.isNotBlank()) {+                    Text(flag)+                }+            }+        } else {+            null+        },         addIcon = { IconCall() },         // Pairs each field with the read-only row on the detail page. A row the user has just         // added has no id yet and no counterpart, so it is left unkeyed.@@ -64,63 +112,109 @@ fun EditContactDetailGroups(         expandOnEnter = true,     ) -    if (!isSimAccount) {-        val emailCtx = LocalContext.current-        FormDetailGroup(-            items = draft.emails,-            label = stringResource(UiR.string.email),-            addLabel = stringResource(R.string.add_email),-            typeOptions = listOf(CDKEmail.TYPE_HOME, CDKEmail.TYPE_WORK, CDKEmail.TYPE_OTHER, CDKEmail.TYPE_MOBILE, CDKEmail.TYPE_CUSTOM),-            value = { it.value },-            onValueChange = { idx, v -> onUpdate(draft.copy(emails = draft.emails.toMutableList().also { l -> l[idx] = l[idx].withValue(v) })) },-            typeLabel = { it.typeString(emailCtx) },-            optionLabel = { opt -> ContactDetail.default<Email>().withType(opt).typeString(emailCtx) },-            onTypeChange = { idx, opt -> onUpdate(draft.copy(emails = draft.emails.toMutableList().also { l -> l[idx] = l[idx].withType(opt) })) },-            onRemove = { idx -> onUpdate(draft.copy(emails = draft.emails.toMutableList().also { l -> l.removeAt(idx) })) },-            onAdd = { onUpdate(draft.copy(emails = draft.emails + ContactDetail.default<Email>())) },-            currentType = { it.type },-            keyboardType = KeyboardType.Email,-            isCustom = { it.type == CDKEmail.TYPE_CUSTOM },-            customLabel = { it.label },-            onLabelChange = { idx, v -> onUpdate(draft.copy(emails = draft.emails.toMutableList().also { l -> l[idx] = l[idx].withLabel(v) })) },-            customLabelText = stringResource(R.string.custom_label),-            customPlaceholder = stringResource(R.string.enter_custom_label),-            addIcon = { IconMail() },-            sharedKey = { it.id.takeIf { id -> id > 0 }?.let { id -> "contact-email-$id" } },-            isMandatory = { it == homeEmailIndex },-            expandOnEnter = true,-        )+    val emailCtx = LocalContext.current+    FormDetailGroup(+        items = draft.emails,+        label = stringResource(UiR.string.email),+        addLabel = stringResource(R.string.add_email),+        typeOptions = listOf(CDKEmail.TYPE_HOME, CDKEmail.TYPE_WORK, CDKEmail.TYPE_OTHER, CDKEmail.TYPE_MOBILE, CDKEmail.TYPE_CUSTOM),+        value = { it.value },+        onValueChange = { idx, v -> onUpdate(draft.copy(emails = draft.emails.toMutableList().also { l -> l[idx] = l[idx].withValue(v) })) },+        typeLabel = { it.typeString(emailCtx) },+        optionLabel = { opt -> ContactDetail.default<Email>().withType(opt).typeString(emailCtx) },+        onTypeChange = { idx, opt -> onUpdate(draft.copy(emails = draft.emails.toMutableList().also { l -> l[idx] = l[idx].withType(opt) })) },+        onRemove = { idx -> onUpdate(draft.copy(emails = draft.emails.toMutableList().also { l -> l.removeAt(idx) })) },+        onAdd = { onUpdate(draft.copy(emails = draft.emails + ContactDetail.default<Email>())) },+        currentType = { it.type },+        keyboardType = KeyboardType.Email,+        isCustom = { it.type == CDKEmail.TYPE_CUSTOM },+        customLabel = { it.label },+        onLabelChange = { idx, v -> onUpdate(draft.copy(emails = draft.emails.toMutableList().also { l -> l[idx] = l[idx].withLabel(v) })) },+        customLabelText = stringResource(R.string.custom_label),+        customPlaceholder = stringResource(R.string.enter_custom_label),+        addIcon = { IconMail() },+        sharedKey = { it.id.takeIf { id -> id > 0 }?.let { id -> "contact-email-$id" } },+        isMandatory = { it == homeEmailIndex },+        expandOnEnter = true,+    ) -        val addressCtx = LocalContext.current-        FormDetailGroup(-            items = draft.addresses,-            label = stringResource(R.string.addresses),-            addLabel = stringResource(R.string.add_address),-            typeOptions = listOf(CDKStructuredPostal.TYPE_HOME, CDKStructuredPostal.TYPE_WORK, CDKStructuredPostal.TYPE_OTHER, CDKStructuredPostal.TYPE_CUSTOM),-            value = { it.value },-            onValueChange = { idx, v -> onUpdate(draft.copy(addresses = draft.addresses.toMutableList().also { l -> l[idx] = l[idx].withValue(v) })) },-            typeLabel = { it.typeString(addressCtx) },-            optionLabel = { opt -> ContactDetail.default<Address>().withType(opt).typeString(addressCtx) },-            onTypeChange = { idx, opt -> onUpdate(draft.copy(addresses = draft.addresses.toMutableList().also { l -> l[idx] = l[idx].withType(opt) })) },-            onRemove = { idx -> onUpdate(draft.copy(addresses = draft.addresses.toMutableList().also { l -> l.removeAt(idx) })) },-            onAdd = { onUpdate(draft.copy(addresses = draft.addresses + ContactDetail.default<Address>())) },-            currentType = { it.type },-            isCustom = { it.type == CDKStructuredPostal.TYPE_CUSTOM },-            customLabel = { it.label },-            onLabelChange = { idx, v -> onUpdate(draft.copy(addresses = draft.addresses.toMutableList().also { l -> l[idx] = l[idx].withLabel(v) })) },-            customLabelText = stringResource(R.string.custom_label),-            customPlaceholder = stringResource(R.string.enter_custom_label),-            addIcon = { IconLocationOn() },-            expandOnEnter = true,+    val addressCtx = LocalContext.current+    FormDetailGroup(+        items = draft.addresses,+        label = stringResource(R.string.addresses),+        addLabel = stringResource(R.string.add_address),+        typeOptions = listOf(CDKStructuredPostal.TYPE_HOME, CDKStructuredPostal.TYPE_WORK, CDKStructuredPostal.TYPE_OTHER, CDKStructuredPostal.TYPE_CUSTOM),+        value = { it.value },+        onValueChange = { idx, v -> onUpdate(draft.copy(addresses = draft.addresses.toMutableList().also { l -> l[idx] = l[idx].withValue(v) })) },+        typeLabel = { it.typeString(addressCtx) },+        optionLabel = { opt -> ContactDetail.default<Address>().withType(opt).typeString(addressCtx) },+        onTypeChange = { idx, opt -> onUpdate(draft.copy(addresses = draft.addresses.toMutableList().also { l -> l[idx] = l[idx].withType(opt) })) },+        onRemove = { idx -> onUpdate(draft.copy(addresses = draft.addresses.toMutableList().also { l -> l.removeAt(idx) })) },+        onAdd = { onUpdate(draft.copy(addresses = draft.addresses + ContactDetail.default<Address>())) },+        currentType = { it.type },+        isCustom = { it.type == CDKStructuredPostal.TYPE_CUSTOM },+        customLabel = { it.label },+        onLabelChange = { idx, v -> onUpdate(draft.copy(addresses = draft.addresses.toMutableList().also { l -> l[idx] = l[idx].withLabel(v) })) },+        customLabelText = stringResource(R.string.custom_label),+        customPlaceholder = stringResource(R.string.enter_custom_label),+        addIcon = { IconLocationOn() },+        expandOnEnter = true,+    )+}++/**+ * Single phone + email fields for SIM accounts. Plain [OutlinedTextField]s rather than+ * [FormDetailGroup]s: one value each, no type selector, no add-more button.+ */+@Composable+internal fun SimContactFields(+    draft: ContactViewModel.ContactDraft,+    onUpdate: (ContactViewModel.ContactDraft) -> Unit,+) {+    val phone = draft.phoneNumbers.take(SIM_MAX_PHONE_NUMBERS).firstOrNull()+    val email = draft.emails.take(SIM_MAX_EMAILS).firstOrNull()+    Column(Modifier.fillMaxWidth()) {+        OutlinedTextField(+            value = phone?.value.orEmpty(),+            onValueChange = { v ->+                val updated = if (phone != null) {+                    draft.phoneNumbers.toMutableList().also { l -> l[0] = l[0].withValue(v) }+                } else {+                    listOf(ContactDetail.default<PhoneNumber>().withType(CDKPhone.TYPE_MOBILE).withValue(v))+                }+                onUpdate(draft.copy(phoneNumbers = updated))+            },+            label = { Text(stringResource(R.string.phone)) },+            singleLine = true,+            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone),+            modifier = Modifier.fillMaxWidth(),+        )+        Spacer(Modifier.height(16.dp))+        OutlinedTextField(+            value = email?.value.orEmpty(),+            onValueChange = { v ->+                val updated = if (email != null) {+                    draft.emails.toMutableList().also { l -> l[0] = l[0].withValue(v) }+                } else {+                    listOf(ContactDetail.default<Email>().withType(CDKEmail.TYPE_HOME).withValue(v))+                }+                onUpdate(draft.copy(emails = updated))+            },+            label = { Text(stringResource(UiR.string.email)) },+            singleLine = true,+            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),+            modifier = Modifier.fillMaxWidth(),         )     } }  internal fun getCountryFlagEmoji(phoneNumber: String): String {+    if (phoneNumber.isBlank()) return ""     val phoneUtil = PhoneNumberUtil.getInstance()     return try {         val numberProto = phoneUtil.parse(phoneNumber, "")-        val regionCode = phoneUtil.getRegionCodeForNumber(numberProto)+        val regionCode = phoneUtil.getRegionCodeForNumber(numberProto) ?: return ""+        if (regionCode.length < 2) return ""         val firstLetter = Character.codePointAt(regionCode, 0) - 0x41 + 0x1F1E6         val secondLetter = Character.codePointAt(regionCode, 1) - 0x41 + 0x1F1E6         String(Character.toChars(firstLetter)) + String(Character.toChars(secondLetter))
contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.ktindex d9fd09575c..47172a9a52 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt@@ -5,11 +5,13 @@ import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import com.vayunmathur.library.ui.R as UiR@@ -42,6 +44,7 @@ import com.vayunmathur.contacts.data.PhoneNumber import com.vayunmathur.contacts.data.SIM_ACCOUNT_TYPE import com.vayunmathur.contacts.util.ContactViewModel import com.vayunmathur.contacts.util.initEditDraft+import com.vayunmathur.contacts.util.loadLastSelectedAccount import com.vayunmathur.contacts.util.saveEditDraft import com.vayunmathur.contacts.util.setLastSelectedAccount import com.vayunmathur.contacts.util.updateEditDraft@@ -55,9 +58,16 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel,     val context = LocalContext.current     var saveError by remember { mutableStateOf<String?>(null) }     var isSaving by remember { mutableStateOf(false) }+    val isNewContact = contactId == null      // Initialize the VM draft for this contact. No-op on rotation (same key).     LaunchedEffect(contactId) {+        // Reload the persisted save location first: after a process kill the+        // in-memory last-selected account is null, and seeding the draft before+        // this runs falls back to on-device despite the stored choice.+        if (isNewContact) {+            viewModel.loadLastSelectedAccount()+        }         viewModel.initEditDraft(             contactId = contactId,             prefill = editRoute.prefill,@@ -66,7 +76,6 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel,     val draft by viewModel.editDraft.collectAsStateWithLifecycle()     val accounts by viewModel.accounts.collectAsStateWithLifecycle()     val simLabels by viewModel.simAccountLabels.collectAsStateWithLifecycle()-    val isNewContact = contactId == null      val pickMedia = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->         if (uri != null) {@@ -100,7 +109,11 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel,         },         bottomBar = {             if (noteController.focused) {-                com.vayunmathur.library.ui.OdfMarkdownEditorToolbar(noteController)+                // Anchored above the IME: without imePadding the bar either floats with+                // a gap (keyboard not yet measured) or sits under the keyboard.+                Box(Modifier.imePadding()) {+                    com.vayunmathur.library.ui.OdfMarkdownEditorToolbar(noteController)+                }             }         },         scrollBehavior = appBarScrollBehavior(),
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelAccounts.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelAccounts.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelAccounts.ktindex bddf5a3538..10b1e95466 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelAccounts.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelAccounts.kt@@ -164,6 +164,12 @@ fun ContactViewModel.loadAccounts() {     } } +/**+ * Reloads the persisted last-selected account (see [setLastSelectedAccount]) into+ * memory. The in-memory state does not survive a process kill, so this must run+ * before a new-contact draft is seeded — otherwise a cold start falls back to the+ * on-device default even though the choice is still in DataStore. Safe to re-call.+ */ fun ContactViewModel.loadLastSelectedAccount() {     val name = dataStore.getString("last_account_name")     val type = dataStore.getString("last_account_type")