Modern Apps git

← Modern-Apps.git

contacts: support add number to contact intent #323

Commit
180ed0e4c1bf274b4d931723e2f1a0814f61c825
Author
Vayun Mathur <[email protected]>
When
2026-07-22 22:27 UTC (4 months ago)
Parents
88e16b3

Diff

contacts/src/main/AndroidManifest.xml
diff --git a/contacts/src/main/AndroidManifest.xml b/contacts/src/main/AndroidManifest.xmlindex 7913817a4f..36969b0470 100644--- a/contacts/src/main/AndroidManifest.xml+++ b/contacts/src/main/AndroidManifest.xml@@ -75,6 +75,28 @@                 <category android:name="android.intent.category.DEFAULT" />             </intent-filter> +            <intent-filter>+                <action android:name="android.intent.action.INSERT_OR_EDIT" />+                <data android:mimeType="vnd.android.cursor.dir/contact" />+                <data android:mimeType="vnd.android.cursor.item/contact" />+                <data android:mimeType="vnd.android.cursor.dir/person" />+                <data android:mimeType="vnd.android.cursor.item/person" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>++            <intent-filter>+                <action android:name="com.android.contacts.action.SHOW_OR_CREATE_CONTACT" />+                <data android:scheme="tel" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>++            <intent-filter>+                <action android:name="com.android.contacts.action.SHOW_OR_CREATE_CONTACT" />+                <data android:mimeType="vnd.android.cursor.dir/contact" />+                <data android:mimeType="vnd.android.cursor.item/contact" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>+             <intent-filter>                 <action android:name="android.intent.action.VIEW" />                 <action android:name="android.intent.action.EDIT" />
contacts/src/main/java/com/vayunmathur/contacts/MainActivity.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/MainActivity.kt b/contacts/src/main/java/com/vayunmathur/contacts/MainActivity.ktindex f85a751b27..e5028e2931 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/MainActivity.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/MainActivity.kt@@ -125,9 +125,14 @@ class MainActivity : ComponentActivity() {         }          val action = intent.action-        if (action == Intent.ACTION_VIEW || action == Intent.ACTION_EDIT || action == Intent.ACTION_INSERT+        if (action == Intent.ACTION_VIEW+            || action == Intent.ACTION_EDIT+            || action == Intent.ACTION_INSERT+            || action == Intent.ACTION_INSERT_OR_EDIT+            || action == ContactsContract.Intents.SHOW_OR_CREATE_CONTACT             || action == ContactsContract.QuickContact.ACTION_QUICK_CONTACT-            || action == "com.android.contacts.action.QUICK_CONTACT") {+            || action == "com.android.contacts.action.QUICK_CONTACT"+        ) {             externalRoute.value = when (action) {                 Intent.ACTION_INSERT -> {                     Route.EditContact(@@ -140,6 +145,16 @@ class MainActivity : ComponentActivity() {                         notes = intent.getStringExtra(ContactsContract.Intents.Insert.NOTES)                     )                 }+                Intent.ACTION_INSERT_OR_EDIT, ContactsContract.Intents.SHOW_OR_CREATE_CONTACT -> {+                    Route.InsertOrEditContact(+                        phone = extractPhoneNumber(intent),+                        name = intent.getStringExtra(ContactsContract.Intents.Insert.NAME),+                        email = intent.getStringExtra(ContactsContract.Intents.Insert.EMAIL),+                        company = intent.getStringExtra(ContactsContract.Intents.Insert.COMPANY),+                        jobTitle = intent.getStringExtra(ContactsContract.Intents.Insert.JOB_TITLE),+                        notes = intent.getStringExtra(ContactsContract.Intents.Insert.NOTES)+                    )+                }                 Intent.ACTION_EDIT -> {                     val contactId = resolveContactId(intent.data)                     Route.EditContact(@@ -333,6 +348,15 @@ fun Navigation(viewModel: ContactViewModel, initialRoute: Route? = null, onExit:             EditContactPage(backStack, viewModel, key, onExit = { goBack() })         } +        entry<Route.InsertOrEditContact>(metadata = ListDetailPage()) { key ->+            InsertOrEditContactScreen(+                viewModel = viewModel,+                backStack = backStack,+                insertOrEditRoute = key,+                onExit = { goBack() }+            )+        }+         entry<Route.Settings>(metadata = ListDetailPage()) {             SettingsPage(viewModel, backStack)         }@@ -402,6 +426,16 @@ sealed interface Route: NavKey {         val notes: String? = null     ) : Route +    @Serializable+    data class InsertOrEditContact(+        val phone: String? = null,+        val name: String? = null,+        val email: String? = null,+        val company: String? = null,+        val jobTitle: String? = null,+        val notes: String? = null+    ) : Route+     @Serializable     data class EventDatePickerDialog(val id: String, val initialDate: LocalDate?): Route 
contacts/src/main/java/com/vayunmathur/contacts/ui/InsertOrEditContactScreen.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/InsertOrEditContactScreen.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/InsertOrEditContactScreen.ktnew file mode 100644index 0000000000..725315d400--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/InsertOrEditContactScreen.kt@@ -0,0 +1,158 @@+package com.vayunmathur.contacts.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.contacts.R+import com.vayunmathur.contacts.Route+import com.vayunmathur.contacts.util.ContactViewModel+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.ui.CommonSearchBar+import com.vayunmathur.library.ui.IconClose++/**+ * Shown for ACTION_INSERT_OR_EDIT / SHOW_OR_CREATE_CONTACT (Fossify dialer "Add number to contact").+ * Lets the user:+ *  - Pick an existing contact โ†’ appends the phone number to that contact+ *  - Create new contact โ†’ navigates to EditContact with the number prefilled+ */+@Composable+fun InsertOrEditContactScreen(+    viewModel: ContactViewModel,+    backStack: NavBackStack<Route>,+    insertOrEditRoute: Route.InsertOrEditContact,+    onExit: () -> Unit+) {+    val phone = insertOrEditRoute.phone+    val contacts by viewModel.contacts.collectAsStateWithLifecycle()+    val searchQuery by viewModel.searchQuery.collectAsStateWithLifecycle()+    var isSaving by remember { mutableStateOf(false) }++    Scaffold(+        topBar = {+            TopAppBar(+                title = {+                    Column {+                        Text(stringResource(R.string.add_number_to_contact))+                        if (!phone.isNullOrBlank()) {+                            Text(phone, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+                        }+                    }+                },+                navigationIcon = {+                    IconButton(onClick = onExit) { IconClose() }+                }+            )+        },+        bottomBar = {+            Row(+                Modifier.fillMaxWidth().padding(16.dp),+                horizontalArrangement = Arrangement.SpaceBetween,+                verticalAlignment = Alignment.CenterVertically+            ) {+                TextButton(onClick = onExit) { Text(stringResource(R.string.cancel)) }+                Button(onClick = {+                    backStack.setLast(+                        Route.EditContact(+                            contactId = null,+                            name = insertOrEditRoute.name,+                            phone = phone,+                            email = insertOrEditRoute.email,+                            company = insertOrEditRoute.company,+                            notes = insertOrEditRoute.notes+                        )+                    )+                }) {+                    Text(stringResource(R.string.create_new_contact))+                }+            }+        }+    ) { padding ->+        Column(Modifier.fillMaxSize().padding(padding)) {+            CommonSearchBar(+                value = searchQuery,+                onValueChange = { viewModel.setSearchQuery(it) },+                placeholder = stringResource(R.string.search_contacts),+                padding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),+                modifier = Modifier.fillMaxWidth()+            )++            if (contacts.isEmpty() && searchQuery.isNotEmpty()) {+                Column(+                    Modifier.fillMaxSize().padding(24.dp),+                    horizontalAlignment = Alignment.CenterHorizontally,+                    verticalArrangement = Arrangement.Center+                ) {+                    Text(stringResource(R.string.no_contacts_found))+                }+            } else {+                val grouped = remember(contacts) {+                    contacts.groupBy { it.name.value.firstOrNull()?.uppercaseChar() ?: '#' }+                        .mapValues { (_, c) -> c.sortedBy { it.name.value } }+                        .toSortedMap()+                }++                LazyColumn(+                    modifier = Modifier.fillMaxSize(),+                    contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp),+                    verticalArrangement = Arrangement.spacedBy(8.dp)+                ) {+                    grouped.forEach { (letter, contactsInGroup) ->+                        item(key = "insedit-header-$letter") { LetterHeader(letter) }+                        item(key = "insedit-card-$letter") {+                            GroupedContactSection(count = contactsInGroup.size) { idx ->+                                val contact = contactsInGroup[idx]+                                ContactItem(+                                    contact = contact,+                                    isSelected = false,+                                    showAccountLabels = true,+                                    viewModel = viewModel,+                                    embeddedInCard = true,+                                    onClick = {+                                        if (isSaving) return@ContactItem+                                        if (phone.isNullOrBlank()) {+                                            backStack.setLast(Route.ContactDetail(contact.id))+                                            return@ContactItem+                                        }+                                        isSaving = true+                                        viewModel.addPhoneNumberToContact(contact.id, phone) {+                                            isSaving = false+                                            backStack.setLast(Route.ContactDetail(contact.id))+                                        }+                                    }+                                )+                            }+                        }+                    }+                }+            }+        }+    }+}
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.ktindex b75bdef061..758bb1ada8 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt@@ -506,6 +506,10 @@ class ContactViewModel(application: Application) : AndroidViewModel(application)      * and/or prefilled fields from a navigation intent. No-op if a draft for the same      * [contactId] already exists โ€” so the user's unsaved edits survive rotation.      */+    private fun normalizePhoneForCompare(raw: String): String {+        return raw.filter { it.isDigit() || it == '+' }.trim()+    }+     fun initEditDraft(         contactId: Long?,         prefillName: String? = null,@@ -536,14 +540,17 @@ class ContactViewModel(application: Application) : AndroidViewModel(application)             accountName = contact?.accountName ?: _lastSelectedAccount.value?.name ?: "",             accountType = contact?.accountType ?: _lastSelectedAccount.value?.type ?: "",             phoneNumbers = (details?.phoneNumbers ?: emptyList()).let { list ->-                if (list.isEmpty() && prefillPhone != null)-                    listOf(PhoneNumber(0, prefillPhone, CDKPhone.TYPE_MOBILE))-                else list+                if (prefillPhone != null) {+                    val normalizedPrefill = normalizePhoneForCompare(prefillPhone)+                    val exists = list.any { normalizePhoneForCompare(it.number) == normalizedPrefill }+                    if (!exists) list + PhoneNumber(0, prefillPhone, CDKPhone.TYPE_MOBILE) else list+                } else list             },             emails = (details?.emails ?: emptyList()).let { list ->-                if (list.isEmpty() && prefillEmail != null)-                    listOf(Email(0, prefillEmail, CDKEmail.TYPE_HOME))-                else list+                if (prefillEmail != null) {+                    val exists = list.any { it.address.trim().equals(prefillEmail.trim(), ignoreCase = true) }+                    if (!exists) list + Email(0, prefillEmail, CDKEmail.TYPE_HOME) else list+                } else list             },             dates = details?.dates ?: emptyList(),             addresses = details?.addresses ?: emptyList(),@@ -551,6 +558,43 @@ class ContactViewModel(application: Application) : AndroidViewModel(application)         )     } +    /**+     * Used by INSERT_OR_EDIT / SHOW_OR_CREATE_CONTACT flow when the user picks an existing+     * contact from the dialer. Directly appends [phone] (if not already present) and saves,+     * without opening the full editor.+     */+    fun addPhoneNumberToContact(+        contactId: Long,+        phone: String,+        type: Int = CDKPhone.TYPE_MOBILE,+        onComplete: () -> Unit = {}+    ) {+        viewModelScope.launch(Dispatchers.IO) {+            try {+                val app = getApplication<Application>()+                // Fetch fresh from provider to avoid stale filtered list.+                val existing = Contact.getContact(app, contactId) ?: _allContacts.value.find { it.id == contactId }+                if (existing == null) {+                    withContext(Dispatchers.Main) { onComplete() }+                    return@launch+                }+                val normalizedNew = normalizePhoneForCompare(phone)+                val alreadyHas = existing.details.phoneNumbers.any { normalizePhoneForCompare(it.number) == normalizedNew }+                if (alreadyHas) {+                    withContext(Dispatchers.Main) { onComplete() }+                    return@launch+                }+                val newDetails = existing.details.copy(+                    phoneNumbers = existing.details.phoneNumbers + PhoneNumber(0, phone, type)+                )+                existing.save(app, newDetails, existing.details)+            } catch (e: Exception) {+                Log.e("ContactViewModel", "Failed to add phone to contact $contactId", e)+            }+            withContext(Dispatchers.Main) { onComplete() }+        }+    }+     /** Applies [transform] to the current draft, if any. */     fun updateEditDraft(transform: (ContactDraft) -> ContactDraft) {         val current = _editDraft.value ?: return
contacts/src/main/res/values/strings.xml
diff --git a/contacts/src/main/res/values/strings.xml b/contacts/src/main/res/values/strings.xmlindex 5c568410a6..392bf36b43 100644--- a/contacts/src/main/res/values/strings.xml+++ b/contacts/src/main/res/values/strings.xml@@ -104,4 +104,6 @@     <string name="select_account">Select account</string>     <string name="no_name">(No name)</string>     <string name="contacts_count">%1$d contacts</string>+    <string name="add_number_to_contact">Add number to contact</string>+    <string name="create_new_contact">Create new contact</string> </resources>\ No newline at end of file