diff options
| author | 2024-07-25 18:43:26 +0000 | |
|---|---|---|
| committer | 2024-07-25 18:43:26 +0000 | |
| commit | 9bd0c7f63c7f1485e3403d102b30e1d58cf0474f (patch) | |
| tree | f62e24db2c27019adcaf44dd5345cf8950364792 | |
| parent | 8b3392e2eb99ec2162737a8da0a7d19e4731bc29 (diff) | |
| parent | e5e09e2af267a7a05069c0cebeed3f7fb3e4f2fe (diff) | |
Merge "Scroll to newly added widget if needed" into main
| -rw-r--r-- | packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt | 34 |
1 files changed, 33 insertions, 1 deletions
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt index 11c104e8542e..b4e513c5137f 100644 --- a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt +++ b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt @@ -216,7 +216,9 @@ fun CommunalHub( val screenWidth = windowMetrics.bounds.width() val layoutDirection = LocalLayoutDirection.current - if (!viewModel.isEditMode) { + if (viewModel.isEditMode) { + ScrollOnNewWidgetAddedEffect(communalContent, gridState) + } else { ScrollOnUpdatedLiveContentEffect(communalContent, gridState) } @@ -547,6 +549,36 @@ private fun ScrollOnUpdatedLiveContentEffect( } } +/** Observes communal content and scrolls to a newly added widget if any. */ +@Composable +private fun ScrollOnNewWidgetAddedEffect( + communalContent: List<CommunalContentModel>, + gridState: LazyGridState, +) { + val coroutineScope = rememberCoroutineScope() + val widgetKeys = remember { mutableListOf<String>() } + + LaunchedEffect(communalContent) { + val oldWidgetKeys = widgetKeys.toList() + widgetKeys.clear() + widgetKeys.addAll(communalContent.filter { it.isWidgetContent() }.map { it.key }) + + // Do nothing if there is no new widget + val indexOfFirstNewWidget = widgetKeys.indexOfFirst { !oldWidgetKeys.contains(it) } + if (indexOfFirstNewWidget < 0) { + return@LaunchedEffect + } + + // Scroll if the new widget is not visible + val lastVisibleItemIndex = gridState.layoutInfo.visibleItemsInfo.lastOrNull()?.index + if (lastVisibleItemIndex != null && indexOfFirstNewWidget > lastVisibleItemIndex) { + // Launching with a scope to prevent the job from being canceled in the case of a + // recomposition during scrolling + coroutineScope.launch { gridState.animateScrollToItem(indexOfFirstNewWidget) } + } + } +} + @OptIn(ExperimentalFoundationApi::class) @Composable private fun BoxScope.CommunalHubLazyGrid( |