Skip to content

Instantly share code, notes, and snippets.

@pflammertsma
Last active September 5, 2024 11:57
Show Gist options
  • Save pflammertsma/83b30c893555fa23e006408b8b3dce75 to your computer and use it in GitHub Desktop.
Save pflammertsma/83b30c893555fa23e006408b8b3dce75 to your computer and use it in GitHub Desktop.
// Copyright 2024 Google LLC.
// SPDX-License-Identifier: Apache-2.0
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun PositionFocusedItemInLazyLayout(
parentFraction: Float = 0.3f,
childFraction: Float = 0f,
content: @Composable () -> Unit,
) {
// This bring-into-view spec pivots around the center of the scrollable container
val bringIntoViewSpec = object : BringIntoViewSpec {
override fun calculateScrollDistance(
// Initial position of item requesting focus
offset: Float,
// Size of item requesting focus
size: Float,
// Size of the lazy container
containerSize: Float
): Float {
val childSmallerThanParent = size <= containerSize
val initialTargetForLeadingEdge =
parentFraction * containerSize - (childFraction * size)
val spaceAvailableToShowItem = containerSize - initialTargetForLeadingEdge
val targetForLeadingEdge =
if (childSmallerThanParent && spaceAvailableToShowItem < size) {
containerSize - size
} else {
initialTargetForLeadingEdge
}
return offset - targetForLeadingEdge
}
}
// LocalBringIntoViewSpec will apply to all scrollables in the hierarchy
CompositionLocalProvider(
LocalBringIntoViewSpec provides bringIntoViewSpec,
content = content,
)
}
// To implement, provide a LazyRow as the PositionFocusedItemInLazyLayout's content
PositionFocusedItemInLazyLayout(parentFraction = 0.5f) {
LazyRow {}
}
@dawidhyzy
Copy link

dawidhyzy commented Jun 27, 2024

Will that be added to tv-foundation once TvLazyLists are removed?

@dawidhyzy
Copy link

dawidhyzy commented Jun 28, 2024

@pflammertsma I used this snippet to document migration from TvLazyLists to LazyLists https://medium.com/@dejwidh/lazylist-pivotoffset-without-tvlazylist-7ad24fe439ab. I hope it's fine.

@pflammertsma
Copy link
Author

Hi Dawid, well observed; we are in the process of bringing scrollable containers back into componse-foundation and this code snippet replaces the pivotOffset parameter.

I will have more to share once we are closer to updating the TV libraries.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment