|
| 1 | +/* |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.facebook.litho.widget |
| 18 | + |
| 19 | +import androidx.annotation.UiThread |
| 20 | +import androidx.core.view.isGone |
| 21 | +import androidx.recyclerview.widget.LinearLayoutManager |
| 22 | +import androidx.recyclerview.widget.RecyclerView |
| 23 | +import com.facebook.litho.ThreadUtils |
| 24 | +import com.facebook.litho.annotations.ExperimentalLithoApi |
| 25 | +import com.facebook.litho.widget.ViewportInfo.ViewportChanged |
| 26 | +import com.facebook.rendercore.Size |
| 27 | +import com.facebook.rendercore.SizeConstraints |
| 28 | +import kotlin.math.max |
| 29 | + |
| 30 | +/** |
| 31 | + * This class is responsible for preparing the items in the collection. It will prepare the items |
| 32 | + * that are in the viewport and the items that are in the range of the viewport. |
| 33 | + */ |
| 34 | +@ExperimentalLithoApi |
| 35 | +class CollectionPreparationManager(private val layoutInfo: LayoutInfo) { |
| 36 | + |
| 37 | + /** |
| 38 | + * The estimated item count in the viewport, which is used to determine the number of items that |
| 39 | + * should be rendered. |
| 40 | + */ |
| 41 | + private var estimatedItemsInViewPort: Int = UNSET |
| 42 | + private var mountedView: RecyclerView? = null |
| 43 | + private var collectionSizeProvider: (() -> Size?)? = null |
| 44 | + private var rangeRatio: Float? = null |
| 45 | + private var onEnterRange: ((Int) -> Unit)? = null |
| 46 | + private var onExitRange: ((Int) -> Unit)? = null |
| 47 | + private var postUpdateViewportAttempts = 0 |
| 48 | + |
| 49 | + private val viewportManager: ViewportManager = |
| 50 | + ViewportManager( |
| 51 | + currentFirstVisiblePosition = RecyclerView.NO_POSITION, |
| 52 | + currentLastVisiblePosition = RecyclerView.NO_POSITION, |
| 53 | + layoutInfo = layoutInfo) |
| 54 | + private val updateViewportRunnable = |
| 55 | + object : Runnable { |
| 56 | + override fun run() { |
| 57 | + val mountedView = mountedView |
| 58 | + if (mountedView == null || !mountedView.hasPendingAdapterUpdates()) { |
| 59 | + if (viewportManager.shouldUpdate()) { |
| 60 | + viewportManager.onViewportChanged(ViewportInfo.State.DATA_CHANGES) |
| 61 | + } |
| 62 | + postUpdateViewportAttempts = 0 |
| 63 | + return |
| 64 | + } |
| 65 | + |
| 66 | + // If the view gets detached, we might still have pending updates. |
| 67 | + // If the view's visibility is GONE, layout won't happen until it becomes visible. We |
| 68 | + // have to exit here, otherwise we keep posting this runnable to the next frame until it |
| 69 | + // becomes visible. |
| 70 | + if (!mountedView.isAttachedToWindow || mountedView.isGone) { |
| 71 | + postUpdateViewportAttempts = 0 |
| 72 | + return |
| 73 | + } |
| 74 | + |
| 75 | + if (postUpdateViewportAttempts >= POST_UPDATE_VIEWPORT_AND_COMPUTE_RANGE_MAX_ATTEMPTS) { |
| 76 | + postUpdateViewportAttempts = 0 |
| 77 | + if (viewportManager.shouldUpdate()) { |
| 78 | + viewportManager.onViewportChanged(ViewportInfo.State.DATA_CHANGES) |
| 79 | + } |
| 80 | + return |
| 81 | + } |
| 82 | + |
| 83 | + // If we have pending updates, wait until the sync operations are finished and try again |
| 84 | + // in the next frame. |
| 85 | + postUpdateViewportAttempts++ |
| 86 | + mountedView.postOnAnimation(this) |
| 87 | + } |
| 88 | + } |
| 89 | + private val viewportChangedListener: ViewportChanged = |
| 90 | + object : ViewportChanged { |
| 91 | + override fun viewportChanged( |
| 92 | + firstVisibleIndex: Int, |
| 93 | + lastVisibleIndex: Int, |
| 94 | + firstFullyVisibleIndex: Int, |
| 95 | + lastFullyVisibleIndex: Int, |
| 96 | + state: Int |
| 97 | + ) { |
| 98 | + viewportManager.resetShouldUpdate() |
| 99 | + maybePostUpdateViewportAndComputeRange(firstVisibleIndex, lastVisibleIndex) |
| 100 | + } |
| 101 | + } |
| 102 | + private val rangeTraverser: RecyclerRangeTraverser |
| 103 | + private val isBound |
| 104 | + get() = |
| 105 | + rangeRatio != null && |
| 106 | + collectionSizeProvider != null && |
| 107 | + onEnterRange != null && |
| 108 | + onExitRange != null |
| 109 | + |
| 110 | + init { |
| 111 | + val layoutManager = layoutInfo.getLayoutManager() |
| 112 | + val stackFromEnd = |
| 113 | + if (layoutManager is LinearLayoutManager) { |
| 114 | + layoutManager.stackFromEnd |
| 115 | + } else { |
| 116 | + false |
| 117 | + } |
| 118 | + rangeTraverser = |
| 119 | + if (stackFromEnd) { |
| 120 | + RecyclerRangeTraverser.BACKWARD_TRAVERSER |
| 121 | + } else { |
| 122 | + RecyclerRangeTraverser.FORWARD_TRAVERSER |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + @UiThread |
| 127 | + fun bind( |
| 128 | + view: RecyclerView, |
| 129 | + rangeRatio: Float, |
| 130 | + collectionSizeProvider: (() -> Size?), |
| 131 | + onEnterRange: (Int) -> Unit, |
| 132 | + onExitRange: (Int) -> Unit |
| 133 | + ) { |
| 134 | + ThreadUtils.assertMainThread() |
| 135 | + this.mountedView = view |
| 136 | + this.rangeRatio = rangeRatio |
| 137 | + this.collectionSizeProvider = collectionSizeProvider |
| 138 | + this.onEnterRange = onEnterRange |
| 139 | + this.onExitRange = onExitRange |
| 140 | + |
| 141 | + view.addOnScrollListener(viewportManager.scrollListener) |
| 142 | + viewportManager.addViewportChangedListener(viewportChangedListener) |
| 143 | + } |
| 144 | + |
| 145 | + @UiThread |
| 146 | + fun unbind(view: RecyclerView) { |
| 147 | + ThreadUtils.assertMainThread() |
| 148 | + view.removeOnScrollListener(viewportManager.scrollListener) |
| 149 | + viewportManager.removeViewportChangedListener(viewportChangedListener) |
| 150 | + mountedView = null |
| 151 | + collectionSizeProvider = null |
| 152 | + rangeRatio = null |
| 153 | + onEnterRange = null |
| 154 | + onExitRange = null |
| 155 | + postUpdateViewportAttempts = 0 |
| 156 | + } |
| 157 | + |
| 158 | + fun addViewportChangedListener(viewportChangedListener: ViewportChanged?) { |
| 159 | + viewportManager.addViewportChangedListener(viewportChangedListener) |
| 160 | + } |
| 161 | + |
| 162 | + /** |
| 163 | + * Attempts to update the viewport and compute the range of items that should be prepared. This |
| 164 | + * method checks if the viewport needs updating and posts a runnable to handle the update. It also |
| 165 | + * triggers computation of which items should enter or exit the preparation range. |
| 166 | + * |
| 167 | + * @param firstVisibleIndex The index of the first visible item in the viewport |
| 168 | + * @param lastVisibleIndex The index of the last visible item in the viewport |
| 169 | + */ |
| 170 | + @UiThread |
| 171 | + fun maybePostUpdateViewportAndComputeRange( |
| 172 | + firstVisibleIndex: Int = layoutInfo.findFirstVisibleItemPosition(), |
| 173 | + lastVisibleIndex: Int = layoutInfo.findLastVisibleItemPosition(), |
| 174 | + ) { |
| 175 | + mountedView?.let { recyclerView -> |
| 176 | + if (viewportManager.shouldUpdate()) { |
| 177 | + recyclerView.removeCallbacks(updateViewportRunnable) |
| 178 | + recyclerView.postOnAnimation(updateViewportRunnable) |
| 179 | + } |
| 180 | + } |
| 181 | + computeRange(firstVisibleIndex, lastVisibleIndex) |
| 182 | + } |
| 183 | + |
| 184 | + /** |
| 185 | + * Computes the range of items that should be prepared for rendering based on the currently |
| 186 | + * visible items. This method determines which items should enter or exit the preparation range |
| 187 | + * based on their position relative to the visible viewport. |
| 188 | + * |
| 189 | + * @param firstVisibleIndex The index of the first visible item in the viewport |
| 190 | + * @param lastVisibleIndex The index of the last visible item in the viewport |
| 191 | + * @param traverser The traverser that defines the order in which items are processed |
| 192 | + */ |
| 193 | + @UiThread |
| 194 | + private fun computeRange( |
| 195 | + firstVisibleIndex: Int, |
| 196 | + lastVisibleIndex: Int, |
| 197 | + traverser: RecyclerRangeTraverser = rangeTraverser, |
| 198 | + ) { |
| 199 | + if (!isBound) return |
| 200 | + |
| 201 | + val collectionSize: Size? = requireNotNull(collectionSizeProvider).invoke() |
| 202 | + if (collectionSize == null || estimatedItemsInViewPort == UNSET) { |
| 203 | + return |
| 204 | + } |
| 205 | + |
| 206 | + val firstVisibleToUse: Int = max(firstVisibleIndex, 0) |
| 207 | + val lastVisibleToUse: Int = max(lastVisibleIndex, 0) |
| 208 | + val rangeSize: Int = max(estimatedItemsInViewPort, lastVisibleToUse - firstVisibleToUse) |
| 209 | + val rangeStart: Int = firstVisibleToUse - (rangeSize * requireNotNull(rangeRatio)).toInt() |
| 210 | + val rangeEnd: Int = |
| 211 | + firstVisibleToUse + rangeSize + (rangeSize * requireNotNull(rangeRatio)).toInt() |
| 212 | + val processor = |
| 213 | + object : RecyclerRangeTraverser.Processor { |
| 214 | + override fun process(index: Int): Boolean = computeAt(index, rangeStart, rangeEnd) |
| 215 | + } |
| 216 | + traverser.traverse(0, layoutInfo.getItemCount(), firstVisibleToUse, lastVisibleToUse, processor) |
| 217 | + } |
| 218 | + |
| 219 | + private fun computeAt(index: Int, rangeStart: Int, rangeEnd: Int): Boolean { |
| 220 | + if (!isBound) return false |
| 221 | + |
| 222 | + if (index >= rangeStart && index <= rangeEnd) { |
| 223 | + requireNotNull(onEnterRange).invoke(index) |
| 224 | + } else { |
| 225 | + requireNotNull(onExitRange).invoke(index) |
| 226 | + } |
| 227 | + return true |
| 228 | + } |
| 229 | + |
| 230 | + /** |
| 231 | + * Estimates the number of items that can fit in the viewport based on measuring a sample item. |
| 232 | + * This calculation is performed only once when estimatedItemsInViewPort is unset and helps |
| 233 | + * determine how many items should be prepared for rendering to optimize performance. |
| 234 | + * |
| 235 | + * @param item A sample CollectionItem used to estimate the size of items in the collection |
| 236 | + * @param sizeConstraintsProvider A function that provides size constraints for measuring the |
| 237 | + * given item |
| 238 | + */ |
| 239 | + fun estimateItemsInViewPort( |
| 240 | + item: CollectionItem<*>, |
| 241 | + sizeConstraintsProvider: (CollectionItem<*>) -> SizeConstraints, |
| 242 | + ) { |
| 243 | + if (!isBound) return |
| 244 | + |
| 245 | + val collectionSize: Size? = requireNotNull(collectionSizeProvider).invoke() |
| 246 | + if (estimatedItemsInViewPort == UNSET && collectionSize != null) { |
| 247 | + val output = IntArray(2) |
| 248 | + item.measure(sizeConstraintsProvider(item), output) |
| 249 | + estimatedItemsInViewPort = |
| 250 | + max( |
| 251 | + layoutInfo.approximateRangeSize( |
| 252 | + output[0], output[1], collectionSize.width, collectionSize.height), |
| 253 | + 1) |
| 254 | + } |
| 255 | + } |
| 256 | + |
| 257 | + companion object { |
| 258 | + private const val UNSET: Int = -1 |
| 259 | + private const val POST_UPDATE_VIEWPORT_AND_COMPUTE_RANGE_MAX_ATTEMPTS: Int = 3 |
| 260 | + } |
| 261 | +} |
0 commit comments