Modern Apps git

← Modern-Apps.git

contacts: themed section scroller with bounded travel

Commit
e0c7c2f6b3051427b115b71c2624c77bfb71f8f9
Author
vayun-mathur <[email protected]>
When
2026-10-24 01:04 UTC (1 month ago)
Parents
7fcef93

Diff

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 83a4acd085..33fb309a93 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt@@ -1,17 +1,5 @@ package com.vayunmathur.contacts.ui -import androidx.compose.foundation.background-import androidx.compose.foundation.gestures.Orientation-import androidx.compose.foundation.gestures.draggable-import androidx.compose.foundation.gestures.rememberDraggableState-import androidx.compose.foundation.gestures.scrollBy-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Spacer-import androidx.compose.foundation.layout.fillMaxHeight-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.width-import androidx.compose.foundation.lazy.LazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue@@ -19,11 +7,8 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalResources-import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.contacts.R import com.vayunmathur.contacts.Route@@ -33,8 +18,6 @@ import com.vayunmathur.contacts.util.ContactListUiState import com.vayunmathur.contacts.util.ContactViewModel import com.vayunmathur.contacts.util.ContactsActions import com.vayunmathur.contacts.util.loadAccounts-import com.vayunmathur.library.ui.FadeVisibility-import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.util.NavBackStack import kotlinx.coroutines.launch @@ -110,60 +93,3 @@ fun ContactList(         },     ) }--/**- * Draggable scrollbar thumb for the contact list.- *- * The list owns its items through `LazyListScaffold`'s internal `LazyColumn`, so the screen- * hoists the [LazyListState] and overlays this thumb: its length and offset mirror the visible- * window, and dragging it scrolls the list, giving hundreds-long address books a fast path- * without leaving the existing list. Hidden for short lists with nothing to jump to.- */-@Composable-internal fun ContactListFastScroller(-    state: LazyListState,-    itemCount: Int,-    modifier: Modifier = Modifier,-) {-    val scope = rememberCoroutineScope()-    val firstIndex = state.firstVisibleItemIndex-    val visibleCount = state.layoutInfo.visibleItemsInfo.size-    FadeVisibility(-        visible = visibleCount > 0 && itemCount > visibleCount,-        modifier = modifier,-    ) {-        val topWeight = firstIndex.toFloat()-        val thumbWeight = visibleCount.toFloat().coerceAtLeast(1f)-        val bottomWeight = (itemCount - firstIndex - visibleCount).toFloat().coerceAtLeast(0f)-        Box(-            modifier = Modifier-                .fillMaxHeight()-                .width(16.dp)-                .draggable(-                    state = rememberDraggableState { delta ->-                        scope.launch { state.scrollBy(delta) }-                    },-                    orientation = Orientation.Vertical,-                ),-            contentAlignment = Alignment.Center,-        ) {-            Column(-                modifier = Modifier-                    .fillMaxHeight()-                    .width(4.dp),-            ) {-                if (topWeight > 0f) Spacer(Modifier.weight(topWeight))-                Box(-                    Modifier-                        .weight(thumbWeight)-                        .fillMaxWidth()-                        .background(-                            MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.45f),-                            MaterialTheme.shapes.small,-                        ),-                )-                if (bottomWeight > 0f) Spacer(Modifier.weight(bottomWeight))-            }-        }-    }-}
contacts/src/main/java/com/vayunmathur/contacts/ui/ContactListScreen.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactListScreen.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactListScreen.ktindex 23986305bd..084297ecb4 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactListScreen.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactListScreen.kt@@ -1,10 +1,7 @@ package com.vayunmathur.contacts.ui  import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState@@ -18,7 +15,6 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.focusProperties import androidx.compose.ui.focus.onFocusChanged-import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.res.pluralStringResource@@ -47,10 +43,8 @@ import com.vayunmathur.library.ui.IconPerson import com.vayunmathur.library.ui.IconShare import com.vayunmathur.library.ui.LazyListScaffold import com.vayunmathur.library.ui.LoadingState-import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OverflowMenu import com.vayunmathur.library.ui.PopVisibility-import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.SwappedTopBar import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton@@ -81,6 +75,21 @@ fun ContactListScreen(             .mapValues { (_, c) -> c.sortedByMode(sortMode) }             .toSortedMap()     }+    // Flat item index of each section header: favorites, then one per letter,+    // in the same order the list emits them (0 is the empty-state/loading slot).+    val sectionIndex = remember(favorites.isNotEmpty(), groupedContacts) {+        buildMap {+            var i = 1+            if (favorites.isNotEmpty()) {+                put(FAVORITES_KEY, 0)+                i += 1 + favorites.size+            }+            for (letter in groupedContacts.keys) {+                put(letter.toString(), i)+                i += 1 + (groupedContacts[letter]?.size ?: 0)+            }+        }+    }      val toggleSelection = { id: Long ->         if (id in selectedIds) selectedIds.remove(id) else selectedIds.add(id)@@ -90,7 +99,7 @@ fun ContactListScreen(      var isFocusableBySystem by remember { mutableStateOf(false) } -    // Hoisted so the fast-scroller thumb below tracks and drives the same list.+    // Hoisted so the section rail below tracks and drives the same list.     val listState = rememberLazyListState()      if (showDeleteConfirmation) {@@ -124,7 +133,6 @@ fun ContactListScreen(         selectedIds.clear()     } -    Box(Modifier.fillMaxSize()) {     LazyListScaffold(         state = listState,         topBar = {@@ -223,6 +231,14 @@ fun ContactListScreen(         // between groups at the 16dp it has always been.         verticalArrangement = Arrangement.spacedBy(2.dp),         scrollBehavior = appBarScrollBehavior(),+        overlay = {+            ContactSectionScroller(+                state = listState,+                sectionIndex = sectionIndex,+                itemCount = listState.layoutInfo.totalItemsCount,+                modifier = Modifier.align(Alignment.CenterEnd),+            )+        },     ) {         if (contacts.isEmpty()) {             item(key = "contacts-empty") {@@ -309,34 +325,4 @@ fun ContactListScreen(             }         }     }-    ContactListFastScroller(-        state = listState,-        itemCount = listState.layoutInfo.totalItemsCount,-        modifier = Modifier.align(Alignment.CenterEnd),-    )-    }-}--/**- * 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,-    ) }
contacts/src/main/java/com/vayunmathur/contacts/ui/ContactSectionScroller.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactSectionScroller.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactSectionScroller.ktnew file mode 100644index 0000000000..06b8c8aa5a--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactSectionScroller.kt@@ -0,0 +1,190 @@+package com.vayunmathur.contacts.ui++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.gestures.detectVerticalDragGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyListState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.IconStar+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text+import kotlinx.coroutines.Job+import kotlinx.coroutines.launch+import kotlin.math.roundToInt++/**+ * Draggable section scrubber for the contact list: a pill on the right edge whose y tracks the+ * scroll fraction, showing the section on screen (★ for favorites, else the letter), with a+ * drag moving the list to the matching position. Always visible.+ *+ * The pill is a Material 3 `secondaryContainer` surface with a `primary` border, so it+ * stays distinguishable from the `surfaceVariant` contact rows in both themes instead of a+ * fixed black/white.+ *+ * [sectionIndex] maps each section key (★, then letters) to its header's flat+ * item index, in list order; the pill position and label derive from the same+ * [LazyListState] so the two never disagree.+ *+ * This must be hosted in [com.vayunmathur.library.ui.LazyListScaffold]'s `overlay` slot (a box+ * exactly the list's size), so the pill travels only along the actual list - hosted full-screen+ * it would run up behind the app bar and down behind the navigation bar.+ */+@Composable+internal fun ContactSectionScroller(+    state: LazyListState,+    sectionIndex: Map<String, Int>,+    itemCount: Int,+    modifier: Modifier = Modifier,+) {+    if (sectionIndex.size < 2) return+    val scope = rememberCoroutineScope()+    var trackHeightPx by remember { mutableIntStateOf(0) }+    var thumbHeightPx by remember { mutableIntStateOf(0) }+    // While dragging, the pill follows the finger exactly (absolute progress along the track)+    // and the list is driven to match - instead of the pill trailing the list state, which+    // lagged behind the finger and let the gesture feel like it kept getting lost.+    var dragging by remember { mutableStateOf(false) }+    var dragProgress by remember { mutableFloatStateOf(0f) }+    var scrollJob by remember { mutableStateOf<Job?>(null) }++    val keys = sectionIndex.keys.toList()+    // The overlay box is the full scaffold content size, including the area behind the app bar and+    // the navigation bar (the list draws under both and insets its *content* instead). Bound the+    // pill's travel to the list's actual viewport - between the top/bottom content padding - so it+    // runs only along the side of the visible list.+    val info = state.layoutInfo+    val topInsetPx = info.beforeContentPadding+    val bottomInsetPx = info.afterContentPadding+    val listViewportPx = (trackHeightPx - topInsetPx - bottomInsetPx).coerceAtLeast(1)+    val travelPx = (listViewportPx - thumbHeightPx).coerceAtLeast(1).toFloat()+    val latestTravelPx = rememberUpdatedState(travelPx)+    val progress = if (dragging) dragProgress else progressOf(state, itemCount)+    val thumbOffsetPx = topInsetPx + progress * travelPx+    val currentKey = keys.lastOrNull { sectionIndex[it]!! <= state.firstVisibleItemIndex } ?: keys.first()++    Box(+        modifier.fillMaxSize(),+    ) {+        // Full-height grab strip on the right edge: starting a vertical drag anywhere in it+        // scrubs the list, so a finger that drifts off the small pill mid-drag no longer falls+        // through to the list itself and stalls the scrub. Horizontal gestures pass through to+        // the list untouched - only vertical drags are claimed.+        Box(+            Modifier+                .align(Alignment.TopEnd)+                .fillMaxHeight()+                .width(64.dp)+                // End the grab strip above the FAB (56dp button + 16dp margin + room), and+                // measure the track here so the pill's travel ends there too.+                .padding(bottom = 88.dp)+                .onSizeChanged { trackHeightPx = it.height }+                // Stable keys: the travel distance is read through updated state, so a+                // recomposition mid-drag never restarts the detector and drops the gesture.+                .pointerInput(itemCount) {+                    detectVerticalDragGestures(+                        onDragStart = {+                            dragging = true+                            dragProgress = progressOf(state, itemCount)+                        },+                        onDragEnd = { dragging = false },+                        onDragCancel = { dragging = false },+                        onVerticalDrag = { change, dragAmount ->+                            change.consume()+                            val p = (dragProgress + dragAmount / latestTravelPx.value).coerceIn(0f, 1f)+                            dragProgress = p+                            val (target, targetOffset) = scrollTargetFor(p, state, itemCount)+                            scrollJob?.cancel()+                            scrollJob = scope.launch { runCatching { state.scrollToItem(target, targetOffset) } }+                        },+                    )+                },+        ) {+            Surface(+                color = MaterialTheme.colorScheme.secondaryContainer,+                shape = MaterialTheme.shapes.large,+                border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary),+                modifier = Modifier+                    .align(Alignment.TopEnd)+                    .offset { IntOffset(0, thumbOffsetPx.roundToInt()) }+                    .padding(end = 8.dp)+                    .onSizeChanged { thumbHeightPx = it.height },+            ) {+                // Fixed size so the star/letter swap never resizes the pill mid-drag (a size+                // change would shift the travel mapping under the finger).+                Box(+                    contentAlignment = Alignment.Center,+                    modifier = Modifier.size(48.dp),+                ) {+                    if (currentKey == FAVORITES_KEY) {+                        IconStar()+                    } else {+                        Text(+                            text = currentKey,+                            style = MaterialTheme.typography.labelLarge,+                        )+                    }+                }+            }+        }+    }+}++/** Favorites section key for the [ContactSectionScroller]. */+internal const val FAVORITES_KEY = "favorites"++/**+ * Scroll fraction 0 (top) to 1 (last item bottom at the viewport bottom):+ * scrolled pixels over the true scrollable distance, so the pill hits the+ * bottom exactly at the list end instead of running ahead of it.+ */+internal fun progressOf(state: LazyListState, itemCount: Int): Float {+    val info = state.layoutInfo+    if (itemCount <= 0) return 0f+    val viewportH = (info.viewportEndOffset - info.viewportStartOffset).coerceAtLeast(1)+    val avgH = info.visibleItemsInfo.map { it.size }.average().takeIf { !it.isNaN() }?.toFloat() ?: 0f+    if (avgH <= 0f) return 0f+    val total = (avgH * itemCount - viewportH).coerceAtLeast(0f)+    if (total <= 0f) return 0f+    val scrolled = state.firstVisibleItemIndex * avgH + state.firstVisibleItemScrollOffset+    return (scrolled / total).coerceIn(0f, 1f)+}++/**+ * Inverse of [progressOf]: the `(index, scrollOffset)` whose scroll fraction equals [progress,+ * so driving the list from a finger position lands where the pill is instead of snapping on+ * release.+ */+internal fun scrollTargetFor(progress: Float, state: LazyListState, itemCount: Int): Pair<Int, Int> {+    val info = state.layoutInfo+    if (itemCount <= 0) return 0 to 0+    val viewportH = (info.viewportEndOffset - info.viewportStartOffset).coerceAtLeast(1)+    val avgH = info.visibleItemsInfo.map { it.size }.average().takeIf { !it.isNaN() }?.toFloat() ?: 0f+    if (avgH <= 0f) return 0 to 0+    val total = (avgH * itemCount - viewportH).coerceAtLeast(0f)+    if (total <= 0f) return 0 to 0+    val scrolled = progress.coerceIn(0f, 1f) * total+    val index = (scrolled / avgH).toInt().coerceIn(0, itemCount - 1)+    val offset = (scrolled - index * avgH).toInt().coerceAtLeast(0)+    return index to offset+}
contacts/src/main/java/com/vayunmathur/contacts/ui/GroupedContactRow.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/GroupedContactRow.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/GroupedContactRow.ktnew file mode 100644index 0000000000..54e533e21d--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/GroupedContactRow.kt@@ -0,0 +1,32 @@+package com.vayunmathur.contacts.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Surface++/**+ * 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+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,+    )+}
library/ui/src/main/java/com/vayunmathur/library/ui/LazyListScaffold.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/LazyListScaffold.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/LazyListScaffold.ktindex adfa8bb4b3..d50f1f5c82 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/LazyListScaffold.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/LazyListScaffold.kt@@ -3,6 +3,8 @@ package com.vayunmathur.library.ui  import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.calculateEndPadding@@ -46,6 +48,10 @@ import androidx.compose.ui.unit.dp  * [paneContentMargin], which is [Spacing.lg] on compact widths; callers that  * already pass their own margin (e.g. 16.dp) can pass [Spacing.lg] explicitly  * to stay fixed, or `0.dp` to opt out entirely.+ *+ * [overlay] is drawn on top of the list in a [Box] exactly the list's size,+ * for chrome that must track the viewport itself - e.g. a fast-scroller whose+ * travel should run along the list, not the whole screen.  */ @Composable fun LazyListScaffold(@@ -63,6 +69,7 @@ fun LazyListScaffold(     expandedWidthPadding: Dp = paneContentMargin(),     verticalArrangement: Arrangement.Vertical = Arrangement.Top,     containerColor: Color = MaterialTheme.colorScheme.background,+    overlay: @Composable BoxScope.() -> Unit = {},     content: LazyListScope.() -> Unit, ) = Scaffold(     modifier.nestedScroll(scrollBehavior.nestedScrollConnection),@@ -82,16 +89,19 @@ fun LazyListScaffold(     // Only the width class above compact adds padding; on phones this is     // exactly [horizontalPadding], unchanged from before.     val extra = (expandedWidthPadding - Spacing.lg).coerceAtLeast(0.dp)-    LazyColumn(-        modifier = Modifier.fillMaxSize(),-        state = state,-        contentPadding = PaddingValues(-            start = pad.calculateStartPadding(dir) + horizontalPadding + extra,-            end = pad.calculateEndPadding(dir) + horizontalPadding + extra,-            top = pad.calculateTopPadding(),-            bottom = pad.calculateBottomPadding(),-        ),-        verticalArrangement = verticalArrangement,-        content = content,-    )+    Box(Modifier.fillMaxSize()) {+        LazyColumn(+            modifier = Modifier.fillMaxSize(),+            state = state,+            contentPadding = PaddingValues(+                start = pad.calculateStartPadding(dir) + horizontalPadding + extra,+                end = pad.calculateEndPadding(dir) + horizontalPadding + extra,+                top = pad.calculateTopPadding(),+                bottom = pad.calculateBottomPadding(),+            ),+            verticalArrangement = verticalArrangement,+            content = content,+        )+        overlay()+    } }