contacts: morph list to detail to edit with expressive motion
- Commit
f9ee241f0b96395274cff42b90d1af5f9c810344- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-29 04:46 UTC (3 months ago)
- Parents
0de0bde
Diff
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 87f9424dbe..d238386108 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/MainActivity.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/MainActivity.kt@@ -388,7 +388,7 @@ fun Navigation(viewModel: ContactViewModel, initialRoute: Route? = null, onExit: ) } - entry<Route.ContactDetail>(metadata = ListDetailPage()) { key ->+ entry<Route.ContactDetail>(metadata = ListDetailPage() + MorphPage()) { key -> ContactDetailsPage( viewModel = viewModel, contactId = key.contactId,@@ -402,7 +402,7 @@ fun Navigation(viewModel: ContactViewModel, initialRoute: Route? = null, onExit: showBackButton = true ) }- entry<Route.EditContact>(metadata = ListDetailPage()) { key ->+ entry<Route.EditContact>(metadata = ListDetailPage() + MorphPage()) { key -> EditContactPage(backStack, viewModel, key, onExit = { goBack() }) }
contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.ktindex d057521348..66efec6c75 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt@@ -43,9 +43,16 @@ import com.vayunmathur.library.ui.DetailLazyColumn import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.util.exitDownward+import com.vayunmathur.library.util.sharedContainer+import com.vayunmathur.library.util.sharedContent import com.vayunmathur.library.ui.Text-import androidx.compose.runtime.Composable import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.compose.animation.core.animateDpAsState+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue import androidx.activity.result.contract.ActivityResultContracts import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.compose.runtime.getValue@@ -55,6 +62,9 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier+import androidx.compose.foundation.layout.FlowRow+import androidx.compose.foundation.layout.offset+import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asImageBitmap@@ -64,6 +74,7 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat import androidx.core.content.FileProvider@@ -106,6 +117,7 @@ import com.vayunmathur.library.ui.ringtonePickerResult import com.vayunmathur.library.ui.ringtoneTitle import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.launch import kotlinx.coroutines.withContext@@ -159,6 +171,7 @@ fun ContactDetailsPage( val groups by viewModel.groups.collectAsStateWithLifecycle() val scope = rememberCoroutineScope()+ val shareContactLabel = stringResource(R.string.share_contact) val ringtonePickerTitle = stringResource(R.string.select_ringtone) val ringtoneLauncher = rememberLauncherForActivityResult(@@ -219,6 +232,14 @@ fun ContactDetailsScreen( val scope = rememberCoroutineScope() + // Only what is on screen when the page arrives should stagger in. A section further down is+ // composed because the user scrolled to it, and delaying that would just feel like lag.+ var arriving by remember { mutableStateOf(true) }+ LaunchedEffect(Unit) {+ delay(StaggerWindowMillis)+ arriving = false+ }+ DetailLazyColumn( title = "", onNavigateBack = if (showBackButton) actions::closeContact else null,@@ -245,21 +266,28 @@ fun ContactDetailsScreen( ) { item {+ // Not staggered: this is where the container transform from the list row lands, and a+ // second entrance animation on top of the morph is what made it look broken before. ProfileHeader(contact, actions::decodePhoto) } item {- ActionButtonsRow(- details.phoneNumbers.firstOrNull()?.number,- details.emails.firstOrNull()?.address,- platforms,- state.isGoogleMeetInstalled- )+ Box(Modifier.staggered(index = 0, arriving = arriving)) {+ ActionButtonsRow(+ details.phoneNumbers.firstOrNull()?.number,+ details.emails.firstOrNull()?.address,+ platforms,+ state.isGoogleMeetInstalled+ )+ } } if (details.phoneNumbers.isNotEmpty()) { item {- Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+ Column(+ modifier = Modifier.staggered(index = 1, arriving = arriving),+ verticalArrangement = Arrangement.spacedBy(2.dp),+ ) { details.phoneNumbers.forEachIndexed { index, phone -> var showCallDropdown by remember(phone.id) { mutableStateOf(false) } var showSmsDropdown by remember(phone.id) { mutableStateOf(false) }@@ -302,6 +330,7 @@ fun ContactDetailsScreen( ) }, shape = groupShape(index, details.phoneNumbers.size),+ modifier = Modifier.sharedContainer("contact-phone-${phone.id}"), ) } }@@ -309,7 +338,10 @@ fun ContactDetailsScreen( } if (details.emails.isNotEmpty()) { item {- Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+ Column(+ modifier = Modifier.staggered(index = 2, arriving = arriving),+ verticalArrangement = Arrangement.spacedBy(2.dp),+ ) { details.emails.forEachIndexed { index, email -> DetailItem( icon = { IconMail() },@@ -319,6 +351,7 @@ fun ContactDetailsScreen( ExternalIntents.sendEmail(context, email.address) }, shape = groupShape(index, details.emails.size),+ modifier = Modifier.sharedContainer("contact-email-${email.id}"), ) } }@@ -422,6 +455,9 @@ fun ContactDetailsScreen( data = group.name, label = stringResource(R.string.groups), shape = groupShape(index, contactGroups.size),+ modifier = Modifier.sharedContainer(+ "contact-group-${contact.id}-${group.id}"+ ), ) } }@@ -437,36 +473,116 @@ fun ContactDetailsScreen( data = ringtoneTitle(context, contact.customRingtone), label = stringResource(R.string.ringtone), onClick = { actions.pickRingtone(contact) },+ // The groups block above this one grows downwards as it morphs into the editor,+ // travelling straight over this row. Fading in place would leave it half-legible+ // underneath; moving with the traveller gets it out of the way.+ modifier = Modifier.exitDownward(), ) } } } } +/**+ * How long after the page appears a section still counts as "arriving".+ *+ * Comfortably longer than the last stagger step plus its spring, so nothing is cut off, but short+ * enough that a section the user scrolls down to is composed past the window and simply appears.+ */+private const val StaggerWindowMillis = 400L+private const val StaggerStepMillis = 45L++/**+ * A short rise-and-fade so the page reads as assembling under the header rather than appearing all at+ * once. [index] is the section's position in that sequence.+ *+ * [arriving] is captured on first composition, not observed: a section composed after the entrance+ * window has been scrolled to, and should be visible immediately rather than animate.+ */+@Composable+private fun Modifier.staggered(index: Int, arriving: Boolean): Modifier {+ var shown by remember { mutableStateOf(!arriving) }+ LaunchedEffect(Unit) {+ if (!shown) {+ delay(index * StaggerStepMillis)+ shown = true+ }+ }+ val motion = MaterialTheme.motionScheme+ val lift by animateDpAsState(if (shown) 0.dp else 12.dp, motion.defaultSpatialSpec())+ val fade by animateFloatAsState(if (shown) 1f else 0f, motion.defaultEffectsSpec())+ return this.offset(y = lift).alpha(fade)+}+ @Composable fun ProfileHeader(contact: Contact, decodePhoto: ((String) -> Bitmap?)? = null) { Column( horizontalAlignment = androidx.compose.ui.Alignment.CenterHorizontally,- modifier = Modifier.fillMaxWidth().padding(vertical = 16.dp)+ // No whole-block shared key. The avatar, each name part and the company pair up individually+ // with their counterparts in the list row and in the editor, and a container morph on top of+ // those would drag the same content to a second destination at the same time.+ modifier = Modifier+ .fillMaxWidth()+ .padding(vertical = 16.dp) ) { ContactAvatar( contact = contact, decodePhoto = decodePhoto,- modifier = Modifier.size(100.dp),+ modifier = Modifier+ .size(100.dp)+ .sharedContent("contact-avatar-${contact.id}"), initialsStyle = MaterialTheme.typography.headlineLarge, ) Spacer(modifier = Modifier.size(16.dp)) - Text(- text = contactDisplayName(contact),- style = MaterialTheme.typography.headlineMedium,- fontWeight = FontWeight.SemiBold+ // Composed from the structured name rather than the joined display name, so that each part can+ // travel to the field that owns it when this page morphs into the editor. A single Text could+ // only ever land in one of them.+ val name = contact.name+ val parts = listOfNotNull(+ name.namePrefix.takeIf { it.isNotBlank() }?.let { "nameprefix" to it },+ name.firstName.takeIf { it.isNotBlank() }?.let { "firstname" to it },+ name.middleName.takeIf { it.isNotBlank() }?.let { "middlename" to it },+ name.lastName.takeIf { it.isNotBlank() }?.let { "lastname" to it },+ name.nameSuffix.takeIf { it.isNotBlank() }?.let { "namesuffix" to it }, )+ FlowRow(+ // Full width so the arrangement always has room to centre within. Without it the row+ // shrinks to its content and relies on the parent Column to centre it, which silently+ // stops working once a name is wide enough to fill the width - the point at which each+ // wrapped line needs centring most.+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(+ 6.dp,+ androidx.compose.ui.Alignment.CenterHorizontally,+ ),+ verticalArrangement = Arrangement.spacedBy(2.dp),+ ) {+ parts.forEach { (slot, text) ->+ Text(+ text = text,+ style = MaterialTheme.typography.headlineMedium,+ fontWeight = FontWeight.SemiBold,+ textAlign = TextAlign.Center,+ modifier = Modifier.sharedContainer("contact-$slot-${contact.id}"),+ )+ }+ }+ if (contact.nickname.nickname.isNotBlank()) {+ Text(+ text = contact.nickname.nickname,+ style = MaterialTheme.typography.titleMedium,+ textAlign = TextAlign.Center,+ modifier = Modifier.sharedContainer("contact-nickname-${contact.id}"),+ )+ } Text( text = contact.org.company, style = MaterialTheme.typography.bodyLarge,- fontWeight = FontWeight.SemiBold+ fontWeight = FontWeight.SemiBold,+ textAlign = TextAlign.Center,+ modifier = Modifier.sharedContainer("contact-company-${contact.id}") ) } }@@ -687,14 +803,14 @@ fun DetailItem( dropdownContent: (@Composable () -> Unit)? = null, trailingDropdownContent: (@Composable () -> Unit)? = null, shape: androidx.compose.ui.graphics.Shape = RoundedCornerShape(16.dp),+ modifier: Modifier = Modifier, ) { val clipboard = LocalClipboard.current val scope = rememberCoroutineScope()- Surface( shape = shape, color = MaterialTheme.colorScheme.surfaceVariant,- modifier = Modifier+ modifier = modifier .fillMaxWidth() .combinedClickable( onClick = onClick ?: { },
contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.ktindex c8959b469f..444fda720f 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt@@ -4,11 +4,24 @@ import androidx.compose.ui.res.pluralStringResource import android.graphics.Bitmap import android.net.Uri import android.provider.ContactsContract+import androidx.compose.animation.AnimatedContent+import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.scaleIn+import androidx.compose.animation.scaleOut+import androidx.compose.animation.slideInVertically+import androidx.compose.animation.slideOutVertically+import androidx.compose.animation.togetherWith+import androidx.compose.animation.core.animateIntAsState import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.combinedClickable+import androidx.compose.foundation.LocalIndication+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column@@ -26,6 +39,7 @@ import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import com.vayunmathur.library.ui.R as UiR@@ -53,6 +67,7 @@ import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import com.vayunmathur.contacts.R import com.vayunmathur.contacts.Route@@ -67,6 +82,8 @@ import com.vayunmathur.contacts.util.ContactSorting.sortedLocale import com.vayunmathur.contacts.util.ContactViewModel import com.vayunmathur.contacts.util.ContactsActions import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.sharedContainer+import com.vayunmathur.library.util.sharedContent import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @@ -160,6 +177,11 @@ fun ContactListScreen(state: ContactListUiState, actions: ContactsActions) { if (id in selectedIds) selectedIds.remove(id) else selectedIds.add(id) } + val motion = MaterialTheme.motionScheme+ val offsetSpec = motion.defaultSpatialSpec<IntOffset>()+ val scaleSpec = motion.defaultSpatialSpec<Float>()+ val fadeSpec = motion.defaultEffectsSpec<Float>()+ var showDeleteConfirmation by remember { mutableStateOf(false) } var isFocusableBySystem by remember { mutableStateOf(false) }@@ -187,8 +209,6 @@ fun ContactListScreen(state: ContactListUiState, actions: ContactsActions) { ) } - val selectedID = state.openContactId- androidx.activity.compose.BackHandler(enabled = state.searchQuery.isNotEmpty() && !isSelectionMode) { actions.setSearchQuery("") }@@ -199,7 +219,17 @@ fun ContactListScreen(state: ContactListUiState, actions: ContactsActions) { LazyListScaffold( topBar = {- if (isSelectionMode) {+ AnimatedContent(+ targetState = isSelectionMode,+ transitionSpec = {+ // Selection slides down over the search field and back up when dismissed, so the+ // two bars read as one surface being swapped rather than two crossfading.+ val towards = if (targetState) -1 else 1+ (fadeIn(fadeSpec) + slideInVertically(offsetSpec) { towards * it / 3 })+ .togetherWith(fadeOut(fadeSpec) + slideOutVertically(offsetSpec) { -towards * it / 3 })+ },+ ) { selecting ->+ if (selecting) { TopAppBar( title = { Text(stringResource(R.string.selected_count, selectedIds.size)) }, navigationIcon = {@@ -254,17 +284,27 @@ fun ContactListScreen(state: ContactListUiState, actions: ContactsActions) { } } )+ } } }, floatingActionButton = {- if(state.showAddButton && !isSelectionMode) {+ // Scales away when selection mode takes over the bar, rather than vanishing. It does not+ // react to scrolling: the add button should always be reachable.+ AnimatedVisibility(+ visible = state.showAddButton && !isSelectionMode,+ enter = scaleIn(scaleSpec) + fadeIn(fadeSpec),+ exit = scaleOut(scaleSpec) + fadeOut(fadeSpec),+ ) { FloatingActionButton(onClick = { actions.addContact() }) { IconAdd() } } }, horizontalPadding = 8.dp,- verticalArrangement = Arrangement.spacedBy(8.dp),+ // 2dp is the gap *within* a grouped card, now that each contact is its own lazy item rather+ // than a row inside one item per letter. The headers carry the extra 6dp that keeps the gap+ // between groups at the 16dp it has always been.+ verticalArrangement = Arrangement.spacedBy(2.dp), scrollBehavior = appBarScrollBehavior(), ) { if (contacts.isEmpty()) {@@ -286,17 +326,26 @@ fun ContactListScreen(state: ContactListUiState, actions: ContactsActions) { } if (favorites.isNotEmpty()) {- item(key = "favorites-header") { FavoritesHeader() }- item(key = "favorites-card") {- GroupedContactSection(count = favorites.size) { idx ->- val contact = favorites[idx]+ item(key = "favorites-header") {+ FavoritesHeader(Modifier.animateItem().padding(vertical = 6.dp))+ }+ itemsIndexed(favorites, key = { _, c -> "favorite-${c.id}" }) { idx, contact ->+ GroupedContactRow(idx, favorites.size, Modifier.animateItem(+ fadeInSpec = fadeSpec,+ placementSpec = offsetSpec,+ fadeOutSpec = fadeSpec,+ )) { ContactItem( contact = contact,- isSelected = if (isSelectionMode) contact.id in selectedIds else selectedID == contact.id,+ // Only multi-select tints the row. It used to also tint whichever contact was+ // open, which meant a plain tap turned the row a different colour at the exact+ // moment it began morphing into the detail page.+ isSelected = isSelectionMode && contact.id in selectedIds, showAccountLabels = state.showAccountLabels, allGroups = state.groups, decodePhoto = actions::decodePhoto, embeddedInCard = true,+ sharedKey = contact.id, onClick = { if (isSelectionMode) toggleSelection(contact.id) else actions.openContact(contact) },@@ -309,17 +358,23 @@ fun ContactListScreen(state: ContactListUiState, actions: ContactsActions) { } groupedContacts.forEach { (letter, contactsInGroup) ->- item(key = "letter-header-$letter") { LetterHeader(letter) }- item(key = "letter-card-$letter") {- GroupedContactSection(count = contactsInGroup.size) { idx ->- val contact = contactsInGroup[idx]+ item(key = "letter-header-$letter") {+ LetterHeader(letter, Modifier.animateItem().padding(vertical = 6.dp))+ }+ itemsIndexed(contactsInGroup, key = { _, c -> "contact-${c.id}" }) { idx, contact ->+ GroupedContactRow(idx, contactsInGroup.size, Modifier.animateItem(+ fadeInSpec = fadeSpec,+ placementSpec = offsetSpec,+ fadeOutSpec = fadeSpec,+ )) { ContactItem( contact = contact,- isSelected = if (isSelectionMode) contact.id in selectedIds else selectedID == contact.id,+ isSelected = isSelectionMode && contact.id in selectedIds, showAccountLabels = state.showAccountLabels, allGroups = state.groups, decodePhoto = actions::decodePhoto, embeddedInCard = true,+ sharedKey = contact.id, onClick = { if (isSelectionMode) toggleSelection(contact.id) else actions.openContact(contact) },@@ -333,6 +388,30 @@ fun ContactListScreen(state: ContactListUiState, actions: ContactsActions) { } } +/**+ * One row of a grouped card, as its own lazy item.+ *+ * The list used to render a whole letter group as a single lazy item wrapping a column of rows, which+ * meant no individual contact was ever a lazy item and `animateItem` had nothing to attach to - so+ * adding or deleting a contact snapped. Splitting them keeps the same rounded-end card look, since+ * only the first and last row of a group are rounded, and [groupShape] already works from an index.+ */+@Composable+private fun GroupedContactRow(+ index: Int,+ count: Int,+ modifier: Modifier = Modifier,+ containerColor: Color = MaterialTheme.colorScheme.surfaceVariant,+ content: @Composable () -> Unit,+) {+ Surface(+ modifier = modifier.fillMaxWidth(),+ shape = groupShape(index, count),+ color = containerColor,+ content = content,+ )+}+ @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -493,10 +572,28 @@ fun ContactItem( onLongClick: (() -> Unit)? = null, dropdownList: List<String>? = null, dropdownListClick: (Int) -> Unit = {},- embeddedInCard: Boolean = false+ embeddedInCard: Boolean = false,+ /**+ * Non-null makes this row the origin of the container transform into the contact's detail page.+ * Null for a row that is a second copy of a contact already shown elsewhere on screen - the+ * morph cannot choose between two origins for one destination.+ */+ sharedKey: Any? = null ) {+ val interaction = remember { MutableInteractionSource() }+ val pressed by interaction.collectIsPressedAsState()+ // The avatar squares off under the finger and springs back on release. A percentage rather than a+ // Dp so it reads the same on the 50dp row avatar and the 100dp one on the detail page, and on the+ // bouncy `fast` spring because a press wants to feel like it gives.+ val avatarCorner by animateIntAsState(+ targetValue = if (pressed) 30 else 50,+ animationSpec = MaterialTheme.motionScheme.fastSpatialSpec(),+ )+ val combinedModifier = if (dropdownList == null) { modifier.combinedClickable(+ interactionSource = interaction,+ indication = LocalIndication.current, onClick = onClick, onLongClick = onLongClick )@@ -532,18 +629,51 @@ fun ContactItem( .padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically ) {- ContactAvatar(contact, decodePhoto, Modifier.size(50.dp))+ ContactAvatar(+ contact,+ decodePhoto,+ Modifier+ .size(50.dp)+ .then(+ if (sharedKey == null) Modifier+ else Modifier.sharedContent("contact-avatar-$sharedKey")+ ),+ shape = RoundedCornerShape(avatarCorner),+ ) Spacer(Modifier.width(16.dp)) Column(modifier = Modifier.weight(1f)) {- Text(- text = contactDisplayName(contact),- style = MaterialTheme.typography.bodyLarge,- fontWeight = FontWeight.Medium,- maxLines = 1,- overflow = TextOverflow.Ellipsis+ // The name is drawn part by part rather than as one joined string, so each piece+ // pairs with the same piece in the detail header and travels there on its own.+ // Morphing the whole row into the whole header instead meant reflowing a+ // horizontal layout into a centred vertical one mid-flight, which read as the row+ // sliding up, snapping to a new layout, then settling.+ val name = contact.name+ val parts = listOfNotNull(+ name.namePrefix.takeIf { it.isNotBlank() }?.let { "nameprefix" to it },+ name.firstName.takeIf { it.isNotBlank() }?.let { "firstname" to it },+ name.middleName.takeIf { it.isNotBlank() }?.let { "middlename" to it },+ name.lastName.takeIf { it.isNotBlank() }?.let { "lastname" to it },+ name.nameSuffix.takeIf { it.isNotBlank() }?.let { "namesuffix" to it }, )+ Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ parts.forEach { (slot, part) ->+ Text(+ text = part,+ style = MaterialTheme.typography.bodyLarge,+ fontWeight = FontWeight.Medium,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = if (sharedKey == null) Modifier+ else Modifier.sharedContainer("contact-$slot-$sharedKey"),+ )+ }+ } if (showOrg) {- Text(trimmedOrg)+ Text(+ text = trimmedOrg,+ modifier = if (sharedKey == null) Modifier+ else Modifier.sharedContainer("contact-company-$sharedKey"),+ ) } if (showGroups) { Text(
contacts/src/main/java/com/vayunmathur/contacts/ui/ContactUiHelpers.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactUiHelpers.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactUiHelpers.ktindex 78c765d990..31529466f0 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactUiHelpers.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactUiHelpers.kt@@ -18,6 +18,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle@@ -59,6 +60,8 @@ fun ContactAvatar( decodePhoto: ((String) -> Bitmap?)?, modifier: Modifier = Modifier, initialsStyle: TextStyle = MaterialTheme.typography.bodyLarge,+ /** Overridable so a caller can morph it - see the press feedback on a contact row. */+ shape: Shape = CircleShape, ) { val photoBase64 = contact.photo?.photo val avatarBitmap by produceState<Bitmap?>(initialValue = null, key1 = photoBase64) {@@ -66,17 +69,17 @@ fun ContactAvatar( withContext(Dispatchers.IO) { decodePhoto?.invoke(photoBase64) } } else null }- Box(modifier.clip(CircleShape), contentAlignment = Alignment.Center) {+ Box(modifier.clip(shape), contentAlignment = Alignment.Center) { val bmp = avatarBitmap if (bmp != null) { Image( bitmap = bmp.asImageBitmap(), contentDescription = stringResource(R.string.contact_photo_description, contact.name.value),- modifier = Modifier.fillMaxSize().clip(CircleShape)+ modifier = Modifier.fillMaxSize().clip(shape) ) } else { Box(- Modifier.fillMaxSize().background(getAvatarColor(contact.id), CircleShape),+ Modifier.fillMaxSize().background(getAvatarColor(contact.id), shape), contentAlignment = Alignment.Center ) { Text(
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 30d60616da..0afd0eb937 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt@@ -14,7 +14,7 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope-import androidx.compose.foundation.layout.FlowRow+import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight@@ -37,8 +37,8 @@ import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.FilledTonalButton import com.vayunmathur.library.ui.FormDetailGroup import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.InputChip import com.vayunmathur.library.ui.LabeledTextField+import com.vayunmathur.library.ui.MultiCategoryPicker import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.DetailScaffold@@ -96,6 +96,8 @@ import com.vayunmathur.library.ui.IconRemoveCircle import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.ResultEffect+import com.vayunmathur.library.util.sharedContainer+import com.vayunmathur.library.util.sharedContent import kotlinx.datetime.LocalDate import kotlin.io.encoding.Base64 @@ -200,7 +202,8 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, }, removePhoto = { viewModel.updateEditDraft { it.copy(photo = null) }- }+ },+ sharedKey = editRoute.contactId, ) Spacer(Modifier.height(24.dp)) @@ -208,6 +211,22 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, // Plain Column rather than FormSection: DetailScaffold already insets its content // horizontally, and the section's own padding on top of that made the name fields // narrower than every field below them.+ // One key per name part, so each piece of the header lands in the field that owns it.+ // Null for a new contact, which has no header to come from. Spelled out rather than built+ // by a helper because a local function cannot be @Composable.+ val id = editRoute.contactId+ val firstNameMod = if (id == null) Modifier.fillMaxWidth()+ else Modifier.sharedContainer("contact-firstname-$id").fillMaxWidth()+ val middleNameMod = if (id == null) Modifier.fillMaxWidth()+ else Modifier.sharedContainer("contact-middlename-$id").fillMaxWidth()+ val lastNameMod = if (id == null) Modifier.fillMaxWidth()+ else Modifier.sharedContainer("contact-lastname-$id").fillMaxWidth()+ val nicknameMod = if (id == null) Modifier.fillMaxWidth()+ else Modifier.sharedContainer("contact-nickname-$id").fillMaxWidth()+ val companyMod = if (id == null) Modifier.fillMaxWidth()+ else Modifier.sharedContainer("contact-company-$id").fillMaxWidth()+ val prefixKey = id?.let { "contact-nameprefix-$it" }+ val suffixKey = id?.let { "contact-namesuffix-$it" } Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp),@@ -216,8 +235,9 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, value = currentDraft.firstName, onValueChange = { v -> viewModel.updateEditDraft { it.copy(firstName = v) } }, label = stringResource(R.string.first_name),+ modifier = firstNameMod, leadingIcon = {- NamePrefixChooser(currentDraft.namePrefix) { v ->+ NamePrefixChooser(currentDraft.namePrefix, prefixKey) { v -> viewModel.updateEditDraft { it.copy(namePrefix = v) } } },@@ -226,13 +246,15 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, value = currentDraft.middleName, onValueChange = { v -> viewModel.updateEditDraft { it.copy(middleName = v) } }, label = stringResource(R.string.middle_name),+ modifier = middleNameMod, ) LabeledTextField( value = currentDraft.lastName, onValueChange = { v -> viewModel.updateEditDraft { it.copy(lastName = v) } }, label = stringResource(R.string.last_name),+ modifier = lastNameMod, trailingIcon = {- NameSuffixChooser(currentDraft.nameSuffix) { v ->+ NameSuffixChooser(currentDraft.nameSuffix, suffixKey) { v -> viewModel.updateEditDraft { it.copy(nameSuffix = v) } } },@@ -241,36 +263,41 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, value = currentDraft.nickname, onValueChange = { v -> viewModel.updateEditDraft { it.copy(nickname = v) } }, label = stringResource(R.string.nickname),+ modifier = nicknameMod, ) LabeledTextField( value = currentDraft.company, onValueChange = { v -> viewModel.updateEditDraft { it.copy(company = v) } }, label = stringResource(R.string.company),+ modifier = companyMod, ) } - // Group memberships (placed near identity fields)- val allGroups by viewModel.groups.collectAsStateWithLifecycle()- val draftGroupIds = currentDraft.groupMemberships.map { it.groupId }.toSet()- val memberGroups = allGroups.filter { it.id in draftGroupIds && it.name.trim().isNotEmpty() }- val availableGroups = allGroups.filter { it.id !in draftGroupIds && it.name.trim().isNotEmpty() }-- GroupMembershipSection(- memberGroups = memberGroups,- availableGroups = availableGroups,- onAddGroup = { groupId ->- viewModel.updateEditDraft { it.copy(- groupMemberships = it.groupMemberships + GroupMembership(0, groupId)- )}- },- onRemoveGroup = { groupId ->- viewModel.updateEditDraft { it.copy(- groupMemberships = it.groupMemberships.filter { gm -> gm.groupId != groupId }- )}+ // 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. Seeded here+ // rather than in the draft so it also applies to contacts saved before this existed.+ val mobileIndex = currentDraft.phoneNumbers.indexOfFirst { it.type == CDKPhone.TYPE_MOBILE }+ val homeEmailIndex = currentDraft.emails.indexOfFirst { it.type == CDKEmail.TYPE_HOME }+ LaunchedEffect(mobileIndex, homeEmailIndex) {+ if (mobileIndex < 0) {+ viewModel.updateEditDraft {+ it.copy(+ phoneNumbers = it.phoneNumbers ++ ContactDetail.default<PhoneNumber>().withType(CDKPhone.TYPE_MOBILE)+ )+ } }- )- Spacer(Modifier.height(16.dp))+ if (homeEmailIndex < 0) {+ viewModel.updateEditDraft {+ it.copy(+ emails = it.emails ++ ContactDetail.default<Email>().withType(CDKEmail.TYPE_HOME)+ )+ }+ }+ } + Spacer(Modifier.height(16.dp)) val phoneCtx = LocalContext.current FormDetailGroup( items = currentDraft.phoneNumbers,@@ -292,6 +319,10 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, customPlaceholder = stringResource(R.string.enter_custom_label), leadingIcon = { item -> Text(getCountryFlagEmoji(item.value)) }, 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.+ sharedKey = { it.id.takeIf { id -> id > 0 }?.let { id -> "contact-phone-$id" } },+ isMandatory = { it == mobileIndex }, ) Spacer(Modifier.height(8.dp)) @@ -315,24 +346,10 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, 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 }, )- Spacer(Modifier.height(16.dp))-- Birthday(backStack, currentDraft.birthday) { v ->- viewModel.updateEditDraft { it.copy(birthday = v) }- }-- DateDetailsSection(- backStack = backStack,- details = currentDraft.dates,- onDetailsChange = { list -> viewModel.updateEditDraft { it.copy(dates = list) } },- icon = { IconEvent() },- options = listOf(CDKEvent.TYPE_ANNIVERSARY, CDKEvent.TYPE_OTHER, CDKEvent.TYPE_CUSTOM)- )-- Spacer(Modifier.height(12.dp))- val addressCtx = LocalContext.current FormDetailGroup( items = currentDraft.addresses,@@ -353,9 +370,18 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, customPlaceholder = stringResource(R.string.enter_custom_label), addIcon = { IconLocationOn() }, )-+ Spacer(Modifier.height(12.dp))+ Birthday(backStack, currentDraft.birthday) { v ->+ viewModel.updateEditDraft { it.copy(birthday = v) }+ }+ DateDetailsSection(+ backStack = backStack,+ details = currentDraft.dates,+ onDetailsChange = { list -> viewModel.updateEditDraft { it.copy(dates = list) } },+ icon = { IconEvent() },+ options = listOf(CDKEvent.TYPE_ANNIVERSARY, CDKEvent.TYPE_OTHER, CDKEvent.TYPE_CUSTOM)+ ) Spacer(Modifier.height(16.dp))- Text( text = stringResource(R.string.note), style = MaterialTheme.typography.labelMedium,@@ -371,6 +397,31 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, .border(1.dp, MaterialTheme.colorScheme.outline, RoundedCornerShape(8.dp)) .padding(12.dp), )+ Spacer(Modifier.height(16.dp))++ // Last, to match the detail page. Anything on both pages is in the same order on both, so+ // a value does not have to be hunted for after the morph, and nothing has to travel past+ // the whole form to reach its counterpart.+ val allGroups by viewModel.groups.collectAsStateWithLifecycle()+ val draftGroupIds = currentDraft.groupMemberships.map { it.groupId }.toSet()+ val memberGroups = allGroups.filter { it.id in draftGroupIds && it.name.trim().isNotEmpty() }+ val availableGroups = allGroups.filter { it.id !in draftGroupIds && it.name.trim().isNotEmpty() }+ GroupMembershipSection(+ memberGroups = memberGroups,+ availableGroups = availableGroups,+ onAddGroup = { groupId ->+ viewModel.updateEditDraft { it.copy(+ groupMemberships = it.groupMemberships + GroupMembership(0, groupId)+ )}+ },+ onRemoveGroup = { groupId ->+ viewModel.updateEditDraft { it.copy(+ groupMemberships = it.groupMemberships.filter { gm -> gm.groupId != groupId }+ )}+ },+ sharedId = editRoute.contactId,+ )+ Spacer(Modifier.height(16.dp)) Spacer(Modifier.height(16.dp)) }@@ -454,25 +505,28 @@ private fun getCountryFlagEmoji(phoneNumber: String): String { /** * The prefix/suffix picker that sits inside the first/last name fields. *- * A chip rather than a bare [TextButton]: it shares the field's background otherwise, so- * there was nothing to show it is a separate value and not part of the name being typed.- * [placeholder] is shown while nothing is chosen, since an empty chip reads as a stray icon.+ * Formatted like the type picker on a phone or email row - a borderless button with its current value+ * and a caret - because that is what it is: a small enumerated choice attached to a field. It used to+ * be an [AssistChip], which read as a tappable object floating in the field rather than as part of it.+ * [placeholder] is shown while nothing is chosen, since an empty label reads as a stray caret. */ @Composable private fun NameAffixChooser( value: String, placeholder: String, options: List<String>,+ sharedKey: Any?, onValueChange: (String) -> Unit, ) { var expanded by remember { mutableStateOf(false) } val none = stringResource(R.string.name_affix_none)- Box {- AssistChip(- onClick = { expanded = true },- label = { Text(value.ifEmpty { placeholder }) },- trailingIcon = { IconArrowDropDown() },- )+ Box(+ if (sharedKey == null) Modifier else Modifier.sharedContainer(sharedKey)+ ) {+ TextButton(onClick = { expanded = true }) {+ Text(value.ifEmpty { placeholder })+ IconArrowDropDown()+ } DropdownMenu(expanded, { expanded = false }) { // The clear option is listed by its localized name but stores an empty affix, so // the contact does not end up with the word "None" as its title.@@ -487,21 +541,23 @@ private fun NameAffixChooser( } @Composable-fun NamePrefixChooser(namePrefix: String, onNamePrefixChange: (String) -> Unit) {+fun NamePrefixChooser(namePrefix: String, sharedKey: Any? = null, onNamePrefixChange: (String) -> Unit) { NameAffixChooser( value = namePrefix, placeholder = stringResource(R.string.name_prefix), options = stringArrayResource(R.array.name_prefixes).toList(),+ sharedKey = sharedKey, onValueChange = onNamePrefixChange, ) } @Composable-fun NameSuffixChooser(nameSuffix: String, onNameSuffixChange: (String) -> Unit) {+fun NameSuffixChooser(nameSuffix: String, sharedKey: Any? = null, onNameSuffixChange: (String) -> Unit) { NameAffixChooser( value = nameSuffix, placeholder = stringResource(R.string.name_suffix), options = stringArrayResource(R.array.name_suffixes).toList(),+ sharedKey = sharedKey, onValueChange = onNameSuffixChange, ) }@@ -528,13 +584,17 @@ private fun Birthday( singleLine = true, modifier = Modifier.fillMaxWidth(), trailingIcon = {- IconButton(onClick = { setBirthday(null) }) {- IconRemoveCircle()+ // There is only ever one birthday, so the row cannot be removed. The button clears the+ // value instead, and is absent while there is nothing to clear.+ if (birthday != null) {+ IconButton(onClick = { setBirthday(null) }) {+ IconRemoveCircle()+ } } } ) // The field is read-only and opens the picker, so the whole row is the tap target -- // except the trailing remove button, which needs its own clicks to reach it.+ // except the trailing clear button, which needs its own clicks to reach it. Row(Modifier.matchParentSize()) { Box( Modifier@@ -542,7 +602,9 @@ private fun Birthday( .fillMaxHeight() .clickable { backStack.add(Route.EventDatePickerDialog("birthday", birthday)) } )- Spacer(Modifier.width(RemoveButtonWidth))+ // Only reserved when the button is actually there, or the right edge of an empty field+ // would not open the picker.+ if (birthday != null) Spacer(Modifier.width(RemoveButtonWidth)) } } @@ -641,69 +703,23 @@ private fun ColumnScope.GroupMembershipSection( memberGroups: List<ContactGroup>, availableGroups: List<ContactGroup>, onAddGroup: (Long) -> Unit,- onRemoveGroup: (Long) -> Unit+ onRemoveGroup: (Long) -> Unit,+ sharedId: Long? = null, ) { if (memberGroups.isEmpty() && availableGroups.isEmpty()) return - Row(- verticalAlignment = Alignment.CenterVertically,- modifier = Modifier.fillMaxWidth()- ) {- IconGroup(- tint = MaterialTheme.colorScheme.onSurfaceVariant,- modifier = Modifier.size(20.dp)- )- Spacer(Modifier.width(8.dp))- Text(- stringResource(R.string.groups),- style = MaterialTheme.typography.labelLarge,- color = MaterialTheme.colorScheme.onSurfaceVariant- )- }- Spacer(Modifier.height(8.dp))-- FlowRow(- horizontalArrangement = Arrangement.spacedBy(8.dp),- verticalArrangement = Arrangement.spacedBy(8.dp),- modifier = Modifier.fillMaxWidth()- ) {- memberGroups.forEach { group ->- InputChip(- selected = false,- onClick = { onRemoveGroup(group.id) },- label = { Text(group.name) },- trailingIcon = {- IconRemoveCircle(modifier = Modifier.size(18.dp))- }- )- }- }-- if (availableGroups.isNotEmpty()) {- Spacer(Modifier.height(4.dp))- var expanded by remember { mutableStateOf(false) }- Box {- FilledTonalButton(- onClick = { expanded = true },- modifier = Modifier.fillMaxWidth()- ) {- IconGroup()- Spacer(Modifier.width(8.dp))- Text(stringResource(R.string.add_to_group))- }- DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {- availableGroups.forEach { group ->- DropdownMenuItem(- text = { Text(group.name) },- onClick = {- onAddGroup(group.id)- expanded = false- }- )- }- }- }- }+ MultiCategoryPicker(+ label = stringResource(R.string.groups),+ selected = memberGroups,+ available = availableGroups,+ itemLabel = { it.name },+ onAdd = { onAddGroup(it.id) },+ onRemove = { onRemoveGroup(it.id) },+ chipModifier = { group ->+ if (sharedId == null) Modifier+ else Modifier.sharedContainer("contact-group-$sharedId-${group.id}")+ },+ ) } @Composable@@ -712,11 +728,23 @@ private fun AddPictureSection( viewModel: ContactViewModel, onClick: () -> Unit, removePhoto: () -> Unit,+ /**+ * Contact id when editing an existing contact, pairing this photo with the avatar on the detail+ * page so the image carries through. Null for a new contact, which has nothing to morph from.+ */+ sharedKey: Any? = null, ) {- Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.clickable(onClick = onClick)) {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ modifier = Modifier.clickable(onClick = onClick),+ ) { Box( modifier = Modifier .size(120.dp)+ .then(+ if (sharedKey == null) Modifier+ else Modifier.sharedContent("contact-avatar-$sharedKey")+ ) .clip(CircleShape) .background(MaterialTheme.colorScheme.secondaryContainer), contentAlignment = Alignment.Center