diff --git a/README.md b/README.md index 93b2029..dcc94b1 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,7 @@ Layout: | `columnWrapperStyle` | `StyleProp` | | Sets the gaps between a grid's columns and rows and its horizontal padding. Other style keys are ignored. | | `inverted` | `boolean` | `false` | Flips the list so the first item shows at the bottom, as in a chat. | | `contentContainerStyle` | `StyleProp` | | Sets the padding, the gaps between rows and the background behind them. `flexGrow` with `justifyContent` places short content, as on FlatList. Other style keys are ignored. | +| `alignItemsAtEnd` | `boolean` | `false` | Places content shorter than the list at its end, as on LegendList. | | `ItemSeparatorComponent` | `ComponentType \| ReactElement` | | Renders a component between React rows, with `leadingItem`, `trailingItem` and `highlighted` as props. Worklet rows take `renderSeparatorCell` instead. | | `separator` | `{ size, color?, insetStart?, insetEnd? }` | | Adds a line `size` dp thick between rows, inset from the start and end edges. | | `stickyHeaderIndices` | `readonly number[]` | | Pins the items at these indices to the top while their section scrolls. | @@ -144,18 +145,28 @@ Scrolling: | `onScrollEndDrag` | `(event) => void` | | Called when the user lifts their finger. | | `onMomentumScrollBegin` | `(event) => void` | | Called when the list starts gliding after a fling. | | `onMomentumScrollEnd` | `(event) => void` | | Called when the list stops gliding. | +| `onScrollToTop` | `(event) => void` | | Called on iOS when the list reaches its top after the user taps the status bar. | +| `scrollsToTop` | `boolean` | `true` when vertical | Scrolls the list to its top on iOS when the user taps the status bar. | | `scrollEnabled` | `boolean` | `true` | Lets the user scroll the list. | | `decelerationRate` | `'normal' \| 'fast' \| number` | `'normal'` | Sets how quickly the list slows down after a fling. | | `showsVerticalScrollIndicator` | `boolean` | `true` | Shows the vertical scroll bar. | | `showsHorizontalScrollIndicator` | `boolean` | `true` | Shows the horizontal scroll bar. | +| `persistentScrollbar` | `boolean` | `false` | Keeps the scroll bar on screen on Android instead of fading it out. | +| `indicatorStyle` | `'default' \| 'black' \| 'white'` | `'default'` | Sets the color of the scroll bars on iOS. | | `keyboardDismissMode` | `'none' \| 'on-drag' \| 'interactive'` | `'none'` | Sets whether dragging the list hides the keyboard. `'interactive'` works on iOS only. | | `keyboardShouldPersistTaps` | `'always' \| 'never' \| 'handled'` | `'never'` | Sets whether the keyboard stays up when the user taps the list, as on ScrollView. | +| `onKeyboardWillShow`, `onKeyboardDidShow`, `onKeyboardWillHide`, `onKeyboardDidHide` | `(event) => void` | | Called with React Native's `Keyboard` events of the same names, as on ScrollView. | | `nestedScrollEnabled` | `boolean` | `false` | Lets the list scroll inside another scrolling view on Android. | | `overScrollMode` | `'auto' \| 'always' \| 'never'` | `'auto'` | Sets when Android shows the overscroll effect at the ends of the list. | | `bounces` | `boolean` | `true` | Bounces the list past its ends on iOS. | | `alwaysBounceVertical` | `boolean` | `true` when vertical | Bounces the list on iOS even when its content is shorter than the list. | +| `alwaysBounceHorizontal` | `boolean` | `true` when horizontal | Bounces a horizontal list on iOS even when its content is narrower than the list. | +| `directionalLockEnabled` | `boolean` | `false` | Keeps a drag on iOS to the direction it started in. | +| `canCancelContentTouches` | `boolean` | `true` | Lets a drag on iOS cancel the touches of native controls inside the rows, as on ScrollView. | +| `scrollToOverflowEnabled` | `boolean` | `false` | Lets `scrollToOffset` scroll past the ends of the content on iOS. | | `contentInset` | `Insets` | | Adds space around the content on iOS. | | `scrollIndicatorInsets` | `Insets` | | Insets the scroll bars on iOS. | +| `automaticallyAdjustsScrollIndicatorInsets` | `boolean` | `true` | Insets the scroll bars on iOS for the safe area. | | `contentInsetAdjustmentBehavior` | `'automatic' \| 'scrollableAxes' \| 'never' \| 'always'` | `'never'` | Sets how iOS insets the content for the safe area. | Visibility, loading and refresh: @@ -171,6 +182,7 @@ Visibility, loading and refresh: | `onRefresh` | `() => void` | | Adds pull to refresh and is called when the user pulls. | | `refreshing` | `boolean` | `false` | Shows the refresh spinner while it's `true`. | | `refreshControl` | `ReactElement \| { tintColor?, colors?, progressViewOffset? }` | | Takes a `RefreshControl` element, as on FlatList, or only the spinner style. `tintColor` works on iOS and `colors` on Android. | +| `progressViewOffset` | `number` | `0` | Moves the refresh spinner down by this many dp, as on FlatList. | The list view: @@ -180,6 +192,7 @@ The list view: | `onLayout` | `(event) => void` | | Called when the list's size or position changes. | | `testID` | `string` | | Sets the ID that tests find the list by. | | `accessibilityLabel` | `string` | | Sets the label that screen readers read for the list. | +| `scrollViewRef`, `refScrollView` | `Ref` | | Gets the object `getScrollResponder()` returns, for code written for FlashList's `scrollViewRef` or LegendList's `refScrollView`. | ### Cells @@ -197,13 +210,21 @@ Define `renderCell` and `renderSeparatorCell` outside your component, or wrap th ### Methods -`scrollToIndex`, `scrollToOffset` and `scrollToEnd` animate unless `animated` is `false`. +The scroll methods animate unless `animated` is `false`. Each returns a Promise that resolves when the list comes to rest, or when a drag, a newer scroll or an unmount stops the scroll first. It never rejects. Type the ref as `useRef>(null)` to await them. | Method | Description | | --- | --- | | `scrollToIndex({ index, animated?, viewPosition?, viewOffset? })` | Scrolls to the item at `index`. A `viewPosition` of 0 puts it at the top, 0.5 in the middle and 1 at the bottom. | +| `scrollToItem({ item, animated?, viewPosition?, viewOffset? })` | Scrolls to `item`, found in `data` by reference. It resolves at once when `item` isn't in `data`. | | `scrollToOffset({ offset, animated? })` | Scrolls to `offset` dp from the start of the content. | +| `scrollToTop({ animated? })` | Scrolls to the start of the list. | | `scrollToEnd({ animated? })` | Scrolls to the end of the list. | +| `scrollIndexIntoView({ index, animated?, viewOffset? })` | Scrolls the item at `index` fully into view at the nearest edge, and leaves the list where it is when the item is already in view. | +| `scrollItemIntoView({ item, animated?, viewOffset? })` | Scrolls `item` fully into view as `scrollIndexIntoView` does. | +| `flashScrollIndicators()` | Shows the scroll bars for a moment. | +| `setNativeProps(props)` | Sets props such as `scrollEnabled` on the native list view without a render. | +| `getScrollResponder()` | Returns an object with ScrollView's `scrollTo`, `scrollToEnd`, `flashScrollIndicators`, `getScrollableNode` and `getNativeScrollRef`. | +| `getNativeScrollRef()` | Returns the native list view. | | `getScrollableNode()` | Returns the native list view. | | `getAnimatableRef()` | Returns the native list view for Animated and Reanimated. | @@ -228,6 +249,10 @@ Then rename `` to ``. `renderItem`, `keyExtractor`, the list co - `stickyHeaderIndices` counts items only. With a `ListHeaderComponent`, subtract 1 from FlatList's indices. - `contentContainerStyle` takes padding, gaps, a background, and `flexGrow` with `justifyContent` to place short content. Other style keys are ignored. - Rows animate when `data` changes and stay in place when items load above them. `itemAnimations` and `maintainVisibleContentPosition` turn this off. +- The scroll methods return a Promise. A ref typed as `FlatList`, `FlashListRef` or `LegendListRef` still fits the `ref` prop. +- Coming from FlashList, flip the sign of `viewOffset`. Flume subtracts it, as FlatList and LegendList do. +- `scrollsToTop` is on for vertical lists only. FlatList turns it on for horizontal lists too. +- `getScrollResponder()` returns an object with ScrollView's scroll methods, not the ScrollView itself. ## Roadmap diff --git a/android/src/main/java/me/sectiontn/flume/FlumeRecyclerView.kt b/android/src/main/java/me/sectiontn/flume/FlumeRecyclerView.kt index 1342b4f..aafc8ae 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeRecyclerView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeRecyclerView.kt @@ -107,7 +107,9 @@ object OverScroll { } } -class FlumeRecyclerView(context: Context) : RecyclerView(context) { +// ScrollView's default style gives the view its themed scroll bars, which a view built in code lacks. +class FlumeRecyclerView(context: Context) : + RecyclerView(context, null, android.R.attr.scrollViewStyle) { var scrollEnabled = true var flingFactor = 1f var keyboardShouldPersistTaps = KeyboardTaps.NEVER @@ -115,6 +117,12 @@ class FlumeRecyclerView(context: Context) : RecyclerView(context) { private val nativeGesture = NativeGestureTracker() private val backgroundPaint = Paint() + init { + // The style enables the vertical bar only. Outside the padding, as React Native's ScrollView draws it. + isHorizontalScrollBarEnabled = true + scrollBarStyle = View.SCROLLBARS_OUTSIDE_OVERLAY + } + // contentContainerStyle's backgroundColor, 0 for none: the rows and their padding, scrolled with them. var contentBackground = 0 set(value) { @@ -125,6 +133,11 @@ class FlumeRecyclerView(context: Context) : RecyclerView(context) { invalidate() } + // ScrollView's flashScrollIndicators: the scroll bars show, then fade as after a scroll. + fun flashScrollIndicators() { + awakenScrollBars() + } + // Under the decorations, so a separator line draws over it. override fun onDraw(c: Canvas) { if (Color.alpha(contentBackground) != 0) drawContentBackground(c) diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index ac7df1e..ecc0678 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -68,10 +68,19 @@ class FlumeView(context: Context) : FrameLayout(context) { get() = scrollState == RecyclerView.SCROLL_STATE_IDLE || !recycler.scrollEnabled // A jump onto React rows waits for the rows it shows; its retained slots are lent to their binds when it runs. - private data class Jump(val position: Int, val animated: Boolean, val viewPosition: Float, val viewOffsetDp: Double, val owner: Int) + private data class Jump(val target: JumpTarget, val animated: Boolean, val viewPosition: Float, val viewOffsetDp: Double, val owner: Int) private val jumps = JumpGate() private val jumpDue = Runnable { jumps.due(SystemClock.uptimeMillis())?.let { runJump(it) } } + private val commands = ScrollCommands() + // The jump of the command in flight once it has run, which new data sends again at its target. + private var landing: Jump? = null + // An instant scroll lands with the next layout pass, an offset glide at its first idle state after it moved. + private var landOnLayout = false + private var landOnIdle = false + private var movedSinceScroll = false + // Bumped by every scroll the view starts, so a stopped smooth scroller of an earlier one lands nothing. + private var scrollToken = 0 private var reclaimOnLayout = false private var reclaimOnIdle = false var emitScrollEvents = false @@ -205,7 +214,10 @@ class FlumeView(context: Context) : FrameLayout(context) { if (index >= 0) emitPress(index, FlumeJni.keyAt(storeId, index), pressId, long) } adapter.onFirstData = { applyInitialScroll() } - adapter.onAutoscroll = { position, viewPosition, animated -> scrollToPosition(position, animated, viewPosition, 0.0) } + adapter.onAutoscroll = { position, viewPosition, animated -> + endScrollCommand() + requestJump(JumpTarget.Position(position), animated, viewPosition, 0.0) + } refreshLayout.addView(recycler, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) refreshLayout.setOnRefreshListener { dispatch(FlumeRefreshEvent(UIManagerHelper.getSurfaceId(this), id)) } addView(slots.parking, LayoutParams(0, 0)) @@ -214,11 +226,24 @@ class FlumeView(context: Context) : FrameLayout(context) { addView(sticky.reactPinned, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)) adapter.onDataChanged = { reset -> viewability.invalidate() + // A command still on its way lands on its target in the new rows, not where anchoring keeps the old ones. + val again = landing?.takeIf { commands.pending != 0 && jumps.pending == null } + if (again != null) { + scrollToken++ + pendingAlign = null + // Begun again before stopScroll, whose idle state would end a command its scroller had landed. + commands.begin(commands.pending) + } if (reset) { recycler.stopScroll() pendingAlign = null } applySpans() + if (again != null) { + requestJump(again.target, again.animated, again.viewPosition, again.viewOffsetDp) + } else { + retargetJump() + } } adapter.onStickyIndicesChanged = { applySpans() } recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() { @@ -243,9 +268,11 @@ class FlumeView(context: Context) : FrameLayout(context) { emitScroll(kind, afterDrag = scrollState == RecyclerView.SCROLL_STATE_DRAGGING) } scrollState = newState + if (newState == RecyclerView.SCROLL_STATE_SETTLING) movedSinceScroll = true if (newState == RecyclerView.SCROLL_STATE_DRAGGING) { pendingAlign = null jumps.cancel()?.let { dropJump(it) } + endScrollCommand() viewability.interacted = true evaluateViewability() if (keyboardDismissOnDrag) recycler.dismissKeyboard() @@ -255,6 +282,11 @@ class FlumeView(context: Context) : FrameLayout(context) { realign() // Inline, so the state is queued before a touch the next looper turn delivers. writeOrigins() + if (landOnIdle && movedSinceScroll) { + landOnIdle = false + commands.land() + } + settleCommand() } if (newState == RecyclerView.SCROLL_STATE_IDLE && reclaimOnIdle) { reclaimOnIdle = false @@ -320,6 +352,11 @@ class FlumeView(context: Context) : FrameLayout(context) { removeCallbacks(realignAfterLayout) post(realignAfterLayout) } + if (landOnLayout) { + landOnLayout = false + commands.land() + } + settleCommand() sticky.refresh() updateEmptyLength() updateFooterLength() @@ -395,21 +432,42 @@ class FlumeView(context: Context) : FrameLayout(context) { } // index counts data items, as FlatList's does; the header and footer are reached by offset and scrollToEnd. - fun scrollToIndex(index: Int, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) { - val target = ScrollTargets.clampIndex(index, rows.dataCount) ?: return - scrollToPosition(rows.position(target), animated, viewPosition, viewOffsetDp) + fun scrollToIndex(id: Int, index: Int, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) { + commands.begin(id) + requestJump(JumpTarget.Index(index), animated, viewPosition, viewOffsetDp) + } + + // A row already fully in view ends the command where the list is. An index past the data lands at the end edge. + fun scrollIndexIntoView(id: Int, index: Int, animated: Boolean, viewOffsetDp: Double) { + commands.begin(id) + val target = JumpTarget.Index(index) + val position = target.position(rows) + val first = layoutManager.findFirstCompletelyVisibleItemPosition() + val last = layoutManager.findLastCompletelyVisibleItemPosition() + val viewPosition = when { + position == null || target.waitsForData(rows) -> 1f + else -> IntoView.target(position, minOf(first, last), maxOf(first, last)) + } + if (viewPosition == null) { + jumps.cancel()?.let { dropJump(it) } + forgetLanding() + landCommand() + return + } + requestJump(target, animated, viewPosition, viewOffsetDp) } // React rows paint a frame or more after their bind, so a jump first has the rows it will show rendered. - private fun scrollToPosition(position: Int, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) { - val target = ScrollTargets.clampIndex(position, rows.itemCount) ?: return + private fun requestJump(target: JumpTarget, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) { jumps.cancel()?.let { dropJump(it) } - val owner = adapter.allocateHolderId() - val window = jumpWindow(target, animated, viewPosition) - val requests = window.filter { isReactRow(it) }.map { adapter.slotRequest(it, viewTypeAt(it)) } - val waiting = slots.reserve(owner, requests) - val jump = Jump(target, animated, viewPosition, viewOffsetDp, owner) - if (waiting.isEmpty()) { + forgetLanding() + if (target.position(rows) == null && !target.waitsForData(rows)) { + landCommand() + return + } + val jump = Jump(target, animated, viewPosition, viewOffsetDp, adapter.allocateHolderId()) + val waiting = reserveJump(jump) + if (waiting.isEmpty() && !target.waitsForData(rows)) { runJump(jump) return } @@ -418,11 +476,68 @@ class FlumeView(context: Context) : FrameLayout(context) { postDelayed(jumpDue, ScrollTargets.JUMP_WAIT_MS) } + // The slots of the React rows the jump shows that have not rendered yet. + private fun reserveJump(jump: Jump): Set { + val position = jump.target.position(rows) ?: return emptySet() + val window = jumpWindow(position, jump.animated, jump.viewPosition) + val requests = window.filter { isReactRow(it) }.map { adapter.slotRequest(it, viewTypeAt(it)) } + return slots.reserve(jump.owner, requests) + } + + // New data moves a waiting jump's target, so it waits for the new rows it shows, before the same deadline. + private fun retargetJump() { + val waiting = jumps.pending ?: return + slots.dropReserved(waiting.owner) + val jump = waiting.copy(owner = adapter.allocateHolderId()) + val slotsLeft = reserveJump(jump) + jumps.retarget(jump, slotsLeft) + if (slotsLeft.isEmpty() && !jump.target.waitsForData(rows)) jumps.cancel()?.let { runJump(it) } + } + private fun runJump(jump: Jump) { removeCallbacks(jumpDue) slots.lend(jump.owner) + val position = jump.target.position(rows) ?: return landCommand() if (jump.animated) reclaimOnIdle = true else reclaimOnLayout = true - startScroll(jump.position, jump.animated, jump.viewPosition, jump.viewOffsetDp) + landing = jump + startScroll(position, jump.animated, jump.viewPosition, jump.viewOffsetDp) + } + + // A new scroll replaces the landing of the one before it. + private fun forgetLanding() { + landing = null + landOnLayout = false + landOnIdle = false + scrollToken++ + } + + private fun landCommand() { + commands.land() + settleCommand() + } + + private fun settleCommand() { + val ended = commands.settle( + ScrollCommands.Rest( + moving = scrollState == RecyclerView.SCROLL_STATE_SETTLING, + dragging = scrollState == RecyclerView.SCROLL_STATE_DRAGGING, + jumpWaiting = jumps.pending != null, + realignPending = pendingAlign != null, + ), + ) + if (ended != 0) { + landing = null + dispatch(FlumeScrollCommandEndEvent(UIManagerHelper.getSurfaceId(this), id, ended)) + } + } + + // A drag, leaving the window, anchoring's own scroll or a dropped view ends the command in flight. + fun endScrollCommand() { + landing = null + landOnLayout = false + landOnIdle = false + val ended = commands.end() + if (ended != 0) dispatch(FlumeScrollCommandEndEvent(UIManagerHelper.getSurfaceId(this), id, ended)) } private fun dropJump(jump: Jump) { @@ -455,7 +570,8 @@ class FlumeView(context: Context) : FrameLayout(context) { } private fun startScroll(position: Int, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) { - val target = ScrollTargets.clampIndex(position, rows.itemCount) ?: return + val target = ScrollTargets.clampIndex(position, rows.itemCount) ?: return landCommand() + val token = scrollToken viewability.interacted = true recycler.stopScroll() val viewOffsetPx = (viewOffsetDp * density).roundToInt() @@ -487,6 +603,7 @@ class FlumeView(context: Context) : FrameLayout(context) { ) } } + scroller.onStopped = { if (token == scrollToken) landCommand() } layoutManager.startSmoothScroll(scroller) return } @@ -494,6 +611,7 @@ class FlumeView(context: Context) : FrameLayout(context) { val itemPx = if (ScrollTargets.needsLength(viewPosition)) rowLengthPx(target) else 0 if (realigns) pendingAlign = PendingAlign(target, viewPosition, viewOffsetPx, itemPx, anchoredAtEnd = anchoredAtEnd) layoutManager.scrollToPositionWithOffset(target, ScrollTargets.offsetPx(viewPosition, viewOffsetPx, viewportPx, itemPx)) + landOnLayout = true } // RecyclerView drops a layout request made inside its own layout pass, so a correction found there waits for the pass to end. @@ -515,6 +633,7 @@ class FlumeView(context: Context) : FrameLayout(context) { } else if (offset != null || (target != null && reactRowsReady())) { pendingAlign = null } + settleCommand() } // The start as scrollToPositionWithOffset counts it: from the padded start edge, or from the end under a reversed layout. @@ -609,15 +728,17 @@ class FlumeView(context: Context) : FrameLayout(context) { } // Offsets count from the content start; the visual delta flips for an inverted list. - fun scrollToOffset(offsetDp: Double, animated: Boolean) { + fun scrollToOffset(id: Int, offsetDp: Double, animated: Boolean) { + commands.begin(id) viewability.interacted = true // Before stopScroll, whose idle state would run an older command's realign. pendingAlign = null jumps.cancel()?.let { dropJump(it) } + forgetLanding() recycler.stopScroll() val targetPx = (offsetDp * density).roundToInt() ScrollTargets.startRow(targetPx)?.let { row -> - scrollToPosition(row, animated, 0f, 0.0) + requestJump(JumpTarget.Position(row), animated, 0f, 0.0) return } val (offsetPx, rangePx, extentPx) = scrollMetrics() @@ -625,10 +746,28 @@ class FlumeView(context: Context) : FrameLayout(context) { val visual = if (inverted) -delta else delta val dx = if (geometry.horizontal) visual else 0 val dy = if (geometry.horizontal) 0 else visual - if (animated) recycler.smoothScrollBy(dx, dy) else recycler.scrollBy(dx, dy) + if (visual != 0 && animated) { + movedSinceScroll = false + landOnIdle = true + recycler.smoothScrollBy(dx, dy) + return + } + if (visual != 0) recycler.scrollBy(dx, dy) + landCommand() } - fun scrollToEnd(animated: Boolean) = scrollToPosition(rows.itemCount - 1, animated, 1f, 0.0) + fun scrollToEnd(id: Int, animated: Boolean) { + commands.begin(id) + requestJump(JumpTarget.End, animated, 1f, 0.0) + } + + // ScrollView's scrollTo carries no command id: it ends the command in flight, then moves along the list's axis. + fun scrollToPoint(xDp: Double, yDp: Double, animated: Boolean) { + endScrollCommand() + scrollToOffset(0, if (geometry.horizontal) xDp else yDp, animated) + } + + fun flashScrollIndicators() = recycler.flashScrollIndicators() fun setListOverScrollMode(value: String?) { recycler.overScrollMode = OverScroll.mode(value) @@ -789,7 +928,7 @@ class FlumeView(context: Context) : FrameLayout(context) { if (initialScrollIndex < rows.dataCount) { layoutManager.scrollToPositionWithOffset(ScrollTargets.initialPosition(initialScrollIndex, rows), 0) } else { - scrollToPosition(ScrollTargets.initialPosition(initialScrollIndex, rows), false, 1f, 0.0) + requestJump(JumpTarget.Position(ScrollTargets.initialPosition(initialScrollIndex, rows)), false, 1f, 0.0) } } @@ -915,6 +1054,9 @@ class FlumeView(context: Context) : FrameLayout(context) { override fun onDetachedFromWindow() { dropMountListener() adapter.detach() + // As on iOS, leaving the window ends a waiting jump and the command in flight. + jumps.cancel()?.let { dropJump(it) } + endScrollCommand() super.onDetachedFromWindow() } diff --git a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt index 2715f92..b49ab74 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt @@ -38,6 +38,7 @@ class FlumeViewManager : ViewGroupManager(), FlumeViewManagerInterfac } override fun onDropViewInstance(view: FlumeView) { + view.endScrollCommand() // A view dropped while detached registered its mount listener after its own detach cleanup. view.dropMountListener() view.setStateWrapper(null) @@ -70,6 +71,7 @@ class FlumeViewManager : ViewGroupManager(), FlumeViewManagerInterfac FlumeEdgeEvent.START to mapOf("registrationName" to "onStartReached"), FlumeRefreshEvent.NAME to mapOf("registrationName" to "onRefresh"), FlumeSlotsEvent.NAME to mapOf("registrationName" to "onSlotsChanged"), + FlumeScrollCommandEndEvent.NAME to mapOf("registrationName" to "onScrollCommandEnd"), ) @ReactProp(name = "itemAnimations", defaultBoolean = true) @@ -297,6 +299,24 @@ class FlumeViewManager : ViewGroupManager(), FlumeViewManagerInterfac override fun setAlwaysBounceVertical(view: FlumeView, value: Boolean) = Unit + override fun setScrollsToTop(view: FlumeView, value: Boolean) = Unit + + override fun setAlwaysBounceHorizontal(view: FlumeView, value: Boolean) = Unit + + override fun setIndicatorStyle(view: FlumeView, value: String?) = Unit + + override fun setDirectionalLockEnabled(view: FlumeView, value: Boolean) = Unit + + override fun setCanCancelContentTouches(view: FlumeView, value: Boolean) = Unit + + override fun setScrollToOverflowEnabled(view: FlumeView, value: Boolean) = Unit + + override fun setAutomaticallyAdjustsScrollIndicatorInsets(view: FlumeView, value: Boolean) = Unit + + override fun setPersistentScrollbar(view: FlumeView, value: Boolean) { + view.recycler.isScrollbarFadingEnabled = !value + } + override fun setRefreshTintColor(view: FlumeView, value: Int?) = Unit @ReactProp(name = "keyboardDismissMode") @@ -312,12 +332,26 @@ class FlumeViewManager : ViewGroupManager(), FlumeViewManagerInterfac view.rowsPressable = value } - override fun scrollToIndex(view: FlumeView, index: Int, animated: Boolean, viewPosition: Double, viewOffset: Double) = - view.scrollToIndex(index, animated, viewPosition.toFloat(), viewOffset) + override fun scrollToIndex( + view: FlumeView, + requestId: Int, + index: Int, + animated: Boolean, + viewPosition: Double, + viewOffset: Double, + ) = view.scrollToIndex(requestId, index, animated, viewPosition.toFloat(), viewOffset) + + override fun scrollToOffset(view: FlumeView, requestId: Int, offset: Double, animated: Boolean) = + view.scrollToOffset(requestId, offset, animated) + + override fun scrollToEnd(view: FlumeView, requestId: Int, animated: Boolean) = view.scrollToEnd(requestId, animated) + + override fun scrollIndexIntoView(view: FlumeView, requestId: Int, index: Int, animated: Boolean, viewOffset: Double) = + view.scrollIndexIntoView(requestId, index, animated, viewOffset) - override fun scrollToOffset(view: FlumeView, offset: Double, animated: Boolean) = view.scrollToOffset(offset, animated) + override fun scrollTo(view: FlumeView, x: Double, y: Double, animated: Boolean) = view.scrollToPoint(x, y, animated) - override fun scrollToEnd(view: FlumeView, animated: Boolean) = view.scrollToEnd(animated) + override fun flashScrollIndicators(view: FlumeView) = view.flashScrollIndicators() override fun setNativeRefreshing(view: FlumeView, refreshing: Boolean) = view.setNativeRefreshing(refreshing) diff --git a/android/src/main/java/me/sectiontn/flume/JumpGate.kt b/android/src/main/java/me/sectiontn/flume/JumpGate.kt index 38d59a4..ff677c5 100644 --- a/android/src/main/java/me/sectiontn/flume/JumpGate.kt +++ b/android/src/main/java/me/sectiontn/flume/JumpGate.kt @@ -16,6 +16,15 @@ class JumpGate(private val waitMs: Long = ScrollTargets.JUMP_WAIT_MS) { return replaced } + // Swaps the waiting jump for one aimed at new rows, keeping its deadline. Returns the old one, or null when none waits. + fun retarget(jump: J, slots: Set): J? { + val replaced = pending ?: return null + pending = jump + waiting.clear() + waiting.addAll(slots) + return replaced + } + fun rendered(slot: Int): J? { if (pending == null || !waiting.remove(slot) || waiting.isNotEmpty()) return null return take() diff --git a/android/src/main/java/me/sectiontn/flume/JumpTarget.kt b/android/src/main/java/me/sectiontn/flume/JumpTarget.kt new file mode 100644 index 0000000..ef3334b --- /dev/null +++ b/android/src/main/java/me/sectiontn/flume/JumpTarget.kt @@ -0,0 +1,21 @@ +package me.sectiontn.flume + +// A scroll command's target in data terms, so a jump that waits through a data change lands on the same index. +sealed interface JumpTarget { + data class Index(val index: Int) : JumpTarget + + // An adapter position, such as the content start or an edge anchoring scrolls to. + data class Position(val position: Int) : JumpTarget + + data object End : JumpTarget + + // The adapter position to land on, or null with no rows. + fun position(rows: ListRows): Int? = when (this) { + is Index -> ScrollTargets.clampIndex(index, rows.dataCount)?.let(rows::position) + is Position -> ScrollTargets.clampIndex(position, rows.itemCount) + End -> ScrollTargets.clampIndex(rows.itemCount - 1, rows.itemCount) + } + + // An index past the data waits for the data to grow, as when new data and the scroll come from one handler. + fun waitsForData(rows: ListRows): Boolean = this is Index && index >= rows.dataCount +} diff --git a/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt b/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt new file mode 100644 index 0000000..2df423b --- /dev/null +++ b/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt @@ -0,0 +1,48 @@ +package me.sectiontn.flume + +// The scroll command in flight: its id is reported once, when it settles at rest or is interrupted. +class ScrollCommands { + data class Rest(val moving: Boolean, val dragging: Boolean, val jumpWaiting: Boolean, val realignPending: Boolean) + + var pending = 0 + private set + private var landed = false + + fun begin(id: Int) { + pending = id + landed = false + } + + // The command's own movement has finished, so a list at rest ends it. + fun land() { + landed = pending != 0 + } + + // Ends the command in flight and returns its id, or 0 when there is none. + fun end(): Int { + val id = pending + reset() + return id + } + + // Ends the command once it has landed and the list rests, else returns 0. + fun settle(rest: Rest): Int { + if (!landed || rest.moving || rest.dragging || rest.jumpWaiting || rest.realignPending) return 0 + return end() + } + + fun reset() { + pending = 0 + landed = false + } +} + +// The viewPosition that brings a row into view: 0 before the fully visible rows, 1 after them, null when it is one. +object IntoView { + fun target(position: Int, firstFull: Int, lastFull: Int): Float? = when { + firstFull < 0 || lastFull < firstFull -> 0f + position < firstFull -> 0f + position > lastFull -> 1f + else -> null + } +} diff --git a/android/src/main/java/me/sectiontn/flume/ScrollEvents.kt b/android/src/main/java/me/sectiontn/flume/ScrollEvents.kt index 5e85e8e..92e6a46 100644 --- a/android/src/main/java/me/sectiontn/flume/ScrollEvents.kt +++ b/android/src/main/java/me/sectiontn/flume/ScrollEvents.kt @@ -149,3 +149,17 @@ class FlumeScrollEvent( putDouble("right", right.toDouble()) } } + +// Every scroll command up to commandId has ended. Never coalesced, so no end the wrapper waits for is replaced. +class FlumeScrollCommandEndEvent(surfaceId: Int, viewTag: Int, val commandId: Int) : + Event(surfaceId, viewTag) { + override fun getEventName(): String = NAME + + override fun canCoalesce(): Boolean = false + + override fun getEventData(): WritableMap = Arguments.createMap().apply { putInt("id", commandId) } + + companion object { + const val NAME = "topScrollCommandEnd" + } +} diff --git a/android/src/main/java/me/sectiontn/flume/ScrollTargets.kt b/android/src/main/java/me/sectiontn/flume/ScrollTargets.kt index b24c637..9a1d9ca 100644 --- a/android/src/main/java/me/sectiontn/flume/ScrollTargets.kt +++ b/android/src/main/java/me/sectiontn/flume/ScrollTargets.kt @@ -115,6 +115,13 @@ class FlumeSmoothScroller( private val msPerPx: Float? = null, ) : LinearSmoothScroller(context) { var onTarget: ((View) -> Unit)? = null + // RecyclerView may still run the last segment after this, so the list rests only at its idle state. + var onStopped: (() -> Unit)? = null + + override fun onStop() { + super.onStop() + onStopped?.invoke() + } override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float = msPerPx ?: super.calculateSpeedPerPixel(displayMetrics) diff --git a/android/src/test/java/me/sectiontn/flume/JumpGateTest.kt b/android/src/test/java/me/sectiontn/flume/JumpGateTest.kt index 9d2baa9..a04beba 100644 --- a/android/src/test/java/me/sectiontn/flume/JumpGateTest.kt +++ b/android/src/test/java/me/sectiontn/flume/JumpGateTest.kt @@ -48,4 +48,37 @@ class JumpGateTest { assertNull(gate.rendered(5)) assertEquals("a", gate.pending) } + + @Test + fun aRetargetKeepsTheFirstDeadline() { + val gate = JumpGate(waitMs = 1000) + gate.request("a", setOf(1), nowMs = 0) + assertEquals("a", gate.retarget("b", setOf(2))) + assertNull(gate.due(nowMs = 999)) + assertEquals("b", gate.due(nowMs = 1000)) + } + + @Test + fun aRetargetWaitsForItsOwnSlots() { + val gate = JumpGate() + gate.request("a", setOf(1), nowMs = 0) + gate.retarget("b", setOf(2)) + assertNull(gate.rendered(1)) + assertEquals("b", gate.rendered(2)) + } + + @Test + fun aRetargetWithNoJumpWaitingDoesNothing() { + val gate = JumpGate() + assertNull(gate.retarget("b", setOf(2))) + assertNull(gate.pending) + } + + @Test + fun aJumpWithNoSlotsWaitsForItsDeadline() { + val gate = JumpGate(waitMs = 1000) + gate.request("a", emptySet(), nowMs = 0) + assertNull(gate.rendered(1)) + assertEquals("a", gate.due(nowMs = 1000)) + } } diff --git a/android/src/test/java/me/sectiontn/flume/JumpTargetTest.kt b/android/src/test/java/me/sectiontn/flume/JumpTargetTest.kt new file mode 100644 index 0000000..0a6fad4 --- /dev/null +++ b/android/src/test/java/me/sectiontn/flume/JumpTargetTest.kt @@ -0,0 +1,45 @@ +package me.sectiontn.flume + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class JumpTargetTest { + private val rows = ListRows(header = true, dataCount = 10, footer = true) + + @Test + fun anIndexLandsOnItsDataRow() { + assertEquals(4, JumpTarget.Index(3).position(rows)) + assertFalse(JumpTarget.Index(3).waitsForData(rows)) + } + + @Test + fun anIndexPastTheDataLandsOnTheLastDataRowAndWaitsForData() { + assertEquals(10, JumpTarget.Index(20).position(rows)) + assertTrue(JumpTarget.Index(20).waitsForData(rows)) + assertTrue(JumpTarget.Index(10).waitsForData(rows)) + } + + @Test + fun theEndIsTheLastRowWithTheFooter() { + assertEquals(11, JumpTarget.End.position(rows)) + assertFalse(JumpTarget.End.waitsForData(rows)) + } + + @Test + fun aPositionStaysInsideTheRows() { + assertEquals(0, JumpTarget.Position(0).position(rows)) + assertEquals(11, JumpTarget.Position(50).position(rows)) + } + + @Test + fun noRowsHaveNoPosition() { + val empty = ListRows() + assertNull(JumpTarget.Index(0).position(empty)) + assertNull(JumpTarget.End.position(empty)) + assertNull(JumpTarget.Position(0).position(empty)) + assertTrue(JumpTarget.Index(0).waitsForData(empty)) + } +} diff --git a/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt b/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt new file mode 100644 index 0000000..9f2ded9 --- /dev/null +++ b/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt @@ -0,0 +1,102 @@ +package me.sectiontn.flume + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class ScrollCommandsTest { + private val rest = ScrollCommands.Rest(moving = false, dragging = false, jumpWaiting = false, realignPending = false) + + @Test + fun endsTheCommandInFlightOnce() { + val commands = ScrollCommands() + commands.begin(3) + assertEquals(3, commands.pending) + assertEquals(3, commands.end()) + assertEquals(0, commands.pending) + assertEquals(0, commands.end()) + } + + @Test + fun reportsNothingWithNoCommand() { + val commands = ScrollCommands() + assertEquals(0, commands.end()) + assertEquals(0, commands.settle(rest)) + } + + @Test + fun aNewerCommandIsTheOneReported() { + val commands = ScrollCommands() + commands.begin(3) + commands.begin(4) + assertEquals(4, commands.end()) + } + + @Test + fun resetForgetsTheCommand() { + val commands = ScrollCommands() + commands.begin(3) + commands.land() + commands.reset() + assertEquals(0, commands.end()) + assertEquals(0, commands.settle(rest)) + } + + @Test + fun anEndAfterResetAndANewCommandReportsTheNewOne() { + val commands = ScrollCommands() + commands.begin(3) + commands.reset() + commands.begin(1) + assertEquals(1, commands.end()) + } + + @Test + fun settlesOnlyAtRest() { + val commands = ScrollCommands() + commands.begin(3) + commands.land() + assertEquals(0, commands.settle(rest.copy(moving = true))) + assertEquals(0, commands.settle(rest.copy(dragging = true))) + assertEquals(0, commands.settle(rest.copy(jumpWaiting = true))) + assertEquals(0, commands.settle(rest.copy(realignPending = true))) + assertEquals(3, commands.settle(rest)) + assertEquals(0, commands.settle(rest)) + } + + @Test + fun doesNotSettleBeforeItLands() { + val commands = ScrollCommands() + commands.begin(3) + assertEquals(0, commands.settle(rest)) + commands.land() + assertEquals(3, commands.settle(rest)) + } + + @Test + fun aNewerCommandClearsTheLandedMark() { + val commands = ScrollCommands() + commands.begin(3) + commands.land() + commands.begin(4) + assertEquals(0, commands.settle(rest)) + } + + @Test + fun intoViewEndsAtOnceForARowFullyInView() { + assertNull(IntoView.target(5, 3, 8)) + assertNull(IntoView.target(3, 3, 8)) + assertNull(IntoView.target(8, 3, 8)) + } + + @Test + fun intoViewScrollsWithViewPosition0BeforeTheVisibleRowsAnd1AfterThem() { + assertEquals(0f, IntoView.target(2, 3, 8)) + assertEquals(1f, IntoView.target(9, 3, 8)) + } + + @Test + fun intoViewPutsTheRowAtTheStartWhenNoRowIsFullyInView() { + assertEquals(0f, IntoView.target(4, -1, -1)) + } +} diff --git a/android/src/test/java/me/sectiontn/flume/ScrollEventsTest.kt b/android/src/test/java/me/sectiontn/flume/ScrollEventsTest.kt index c984f4b..217dca2 100644 --- a/android/src/test/java/me/sectiontn/flume/ScrollEventsTest.kt +++ b/android/src/test/java/me/sectiontn/flume/ScrollEventsTest.kt @@ -48,4 +48,14 @@ class ScrollEventsTest { // Across a horizontal list: 4 left and 6 right of a 360 px viewport leave an extent of 350. assertEquals(Pair(1000 - 350 + 360, 300), ScrollMetrics.contentSizePx(true, 1000, padding, 360, 300)) } + + @Test + fun theCommandEndEventNeverCoalesces() { + assertFalse(FlumeScrollCommandEndEvent(1, 2, 7).canCoalesce()) + } + + @Test + fun theCommandEndEventCarriesTheId() { + assertEquals(7, FlumeScrollCommandEndEvent(1, 2, 7).commandId) + } } diff --git a/cpp/adapter/JumpGate.h b/cpp/adapter/JumpGate.h index d65f69e..2ac4ec5 100644 --- a/cpp/adapter/JumpGate.h +++ b/cpp/adapter/JumpGate.h @@ -24,6 +24,14 @@ class JumpGate { return replaced; } + // Swaps the waiting jump for one aimed at new rows, keeping its deadline. Returns the old one, or nothing when none waits. + std::optional retarget(Jump jump, std::unordered_set slots) { + if (!pending_) return std::nullopt; + std::optional replaced = std::exchange(pending_, std::move(jump)); + waiting_ = std::move(slots); + return replaced; + } + std::optional rendered(int slot) { if (!pending_ || waiting_.erase(slot) == 0 || !waiting_.empty()) return std::nullopt; return take(); diff --git a/cpp/adapter/ScrollCommands.cpp b/cpp/adapter/ScrollCommands.cpp new file mode 100644 index 0000000..63b766b --- /dev/null +++ b/cpp/adapter/ScrollCommands.cpp @@ -0,0 +1,39 @@ +#include "adapter/ScrollCommands.h" + +namespace flume { + +void ScrollCommands::begin(int32_t id) { + id_ = id; + landed_ = false; +} + +void ScrollCommands::land() { landed_ = id_ != 0; } + +int32_t ScrollCommands::end() { + const int32_t id = id_; + reset(); + return id; +} + +int32_t ScrollCommands::settle(const Rest& rest) { + if (!landed_ || rest.moving || rest.dragging || rest.jumpWaiting || rest.realignPending) return 0; + return end(); +} + +void ScrollCommands::reset() { + id_ = 0; + landed_ = false; +} + +} // namespace flume + +namespace flume { + +std::optional intoViewPosition(int position, int firstFull, int lastFull) { + if (firstFull < 0 || lastFull < firstFull) return 0.f; + if (position < firstFull) return 0.f; + if (position > lastFull) return 1.f; + return std::nullopt; +} + +} // namespace flume diff --git a/cpp/adapter/ScrollCommands.h b/cpp/adapter/ScrollCommands.h new file mode 100644 index 0000000..2ba5618 --- /dev/null +++ b/cpp/adapter/ScrollCommands.h @@ -0,0 +1,51 @@ +#pragma once + +#include +#include +#include + +namespace flume { + +// The viewPosition that brings a row into view: 0 before the fully visible rows, 1 after them, none when it is one. +// Positions count list rows. With no row fully in view, the row goes to the start. +std::optional intoViewPosition(int position, int firstFull, int lastFull); + +// The scroll command in flight: its id is reported once, when it settles at rest or is interrupted. +class ScrollCommands { + public: + struct Rest { + bool moving = false; + bool dragging = false; + bool jumpWaiting = false; + bool realignPending = false; + }; + + void begin(int32_t id); + // The command's own movement has finished, so a list at rest ends it. + void land(); + // Ends the command in flight and returns its id, or 0 when there is none. + int32_t end(); + // Ends the command once it has landed and the list rests, else returns 0. + int32_t settle(const Rest& rest); + int32_t pending() const { return id_; } + void reset(); + + private: + int32_t id_ = 0; + bool landed_ = false; +}; + +// The status bar tap that scrolls through the jump gate: the end of its glide reports the scroll to top, once. +class TopTap { + public: + void begin() { pending_ = true; } + // A drag or a newer scroll took the list over. + void cancel() { pending_ = false; } + // True once, for the glide the tap started. + bool glideEnded() { return std::exchange(pending_, false); } + + private: + bool pending_ = false; +}; + +} // namespace flume diff --git a/cpp/adapter/ScrollEvents.h b/cpp/adapter/ScrollEvents.h index ad9d89c..f20b483 100644 --- a/cpp/adapter/ScrollEvents.h +++ b/cpp/adapter/ScrollEvents.h @@ -4,7 +4,7 @@ namespace flume { -enum class ScrollEventKind { Scroll, BeginDrag, EndDrag, MomentumBegin, MomentumEnd }; +enum class ScrollEventKind { Scroll, BeginDrag, EndDrag, MomentumBegin, MomentumEnd, ScrollToTop }; // React Native's iOS rules: the throttle, and which events each UIScrollView callback sends. class ScrollEvents { diff --git a/cpp/tests/jump_gate_test.cpp b/cpp/tests/jump_gate_test.cpp index 13d528e..51d4a64 100644 --- a/cpp/tests/jump_gate_test.cpp +++ b/cpp/tests/jump_gate_test.cpp @@ -44,3 +44,32 @@ TEST_CASE("a rendered slot of no jump is ignored") { CHECK_FALSE(gate.rendered(5)); CHECK(gate.pending() == "a"); } + +TEST_CASE("a retarget keeps the first deadline") { + JumpGate gate(1000); + gate.request("a", {1}, 0); + CHECK(gate.retarget("b", {2}) == "a"); + CHECK_FALSE(gate.due(999)); + CHECK(gate.due(1000) == "b"); +} + +TEST_CASE("a retarget waits for its own slots") { + JumpGate gate; + gate.request("a", {1}, 0); + gate.retarget("b", {2}); + CHECK_FALSE(gate.rendered(1)); + CHECK(gate.rendered(2) == "b"); +} + +TEST_CASE("a retarget with no jump waiting does nothing") { + JumpGate gate; + CHECK_FALSE(gate.retarget("b", {2})); + CHECK_FALSE(gate.pending()); +} + +TEST_CASE("a jump with no slots waits for its deadline") { + JumpGate gate(1000); + gate.request("a", {}, 0); + CHECK_FALSE(gate.rendered(1)); + CHECK(gate.due(1000) == "a"); +} diff --git a/cpp/tests/scroll_commands_test.cpp b/cpp/tests/scroll_commands_test.cpp new file mode 100644 index 0000000..a184670 --- /dev/null +++ b/cpp/tests/scroll_commands_test.cpp @@ -0,0 +1,112 @@ +#include "doctest.h" + +#include "adapter/ScrollCommands.h" + +using namespace flume; + +namespace { + +constexpr ScrollCommands::Rest kRest{}; + +} // namespace + +TEST_CASE("ScrollCommands ends the command in flight once") { + ScrollCommands commands; + commands.begin(3); + CHECK(commands.pending() == 3); + CHECK(commands.end() == 3); + CHECK(commands.pending() == 0); + CHECK(commands.end() == 0); +} + +TEST_CASE("ScrollCommands reports nothing with no command") { + ScrollCommands commands; + CHECK(commands.end() == 0); + CHECK(commands.settle(kRest) == 0); +} + +TEST_CASE("ScrollCommands a newer command is the one reported") { + ScrollCommands commands; + commands.begin(3); + commands.begin(4); + CHECK(commands.end() == 4); +} + +TEST_CASE("ScrollCommands reset forgets the command") { + ScrollCommands commands; + commands.begin(3); + commands.land(); + commands.reset(); + CHECK(commands.end() == 0); + CHECK(commands.settle(kRest) == 0); +} + +TEST_CASE("ScrollCommands an end after reset and a new command reports the new one") { + ScrollCommands commands; + commands.begin(3); + commands.reset(); + commands.begin(1); + CHECK(commands.end() == 1); +} + +TEST_CASE("ScrollCommands settles only at rest") { + ScrollCommands commands; + commands.begin(3); + commands.land(); + CHECK(commands.settle({.moving = true}) == 0); + CHECK(commands.settle({.dragging = true}) == 0); + CHECK(commands.settle({.jumpWaiting = true}) == 0); + CHECK(commands.settle({.realignPending = true}) == 0); + CHECK(commands.settle(kRest) == 3); + CHECK(commands.settle(kRest) == 0); +} + +TEST_CASE("ScrollCommands does not settle before it lands") { + ScrollCommands commands; + commands.begin(3); + CHECK(commands.settle(kRest) == 0); + commands.land(); + CHECK(commands.settle(kRest) == 3); +} + +TEST_CASE("ScrollCommands a newer command clears the landed mark") { + ScrollCommands commands; + commands.begin(3); + commands.land(); + commands.begin(4); + CHECK(commands.settle(kRest) == 0); +} + +TEST_CASE("IntoView ends at once for a row fully in view") { + CHECK_FALSE(intoViewPosition(5, 3, 8).has_value()); + CHECK_FALSE(intoViewPosition(3, 3, 8).has_value()); + CHECK_FALSE(intoViewPosition(8, 3, 8).has_value()); +} + +TEST_CASE("IntoView scrolls with viewPosition 0 before the visible rows and 1 after them") { + CHECK(intoViewPosition(2, 3, 8) == 0.f); + CHECK(intoViewPosition(9, 3, 8) == 1.f); +} + +TEST_CASE("IntoView puts the row at the start when no row is fully in view") { + CHECK(intoViewPosition(4, -1, -1) == 0.f); +} + +TEST_CASE("TopTap: the status bar tap's glide reports scroll to top at its end") { + TopTap tap; + tap.begin(); + CHECK(tap.glideEnded()); + CHECK_FALSE(tap.glideEnded()); +} + +TEST_CASE("TopTap: a glide with no tap behind it reports nothing") { + TopTap tap; + CHECK_FALSE(tap.glideEnded()); +} + +TEST_CASE("TopTap: a drag or a newer scroll cancels the report") { + TopTap tap; + tap.begin(); + tap.cancel(); + CHECK_FALSE(tap.glideEnded()); +} diff --git a/example/src/screens/ChatScreen.tsx b/example/src/screens/ChatScreen.tsx index 573edca..6b9397d 100644 --- a/example/src/screens/ChatScreen.tsx +++ b/example/src/screens/ChatScreen.tsx @@ -1,5 +1,5 @@ import { useMemo, useRef, useState } from 'react'; -import { Button, Platform, ToastAndroid, View } from 'react-native'; +import { Button, Platform, Text, ToastAndroid, View } from 'react-native'; import { Flume, type FlumeRef, type PressInfo } from 'react-native-flume'; import { accentColor, @@ -9,6 +9,7 @@ import { makeRenderCell, makeRenderSeparatorCell, } from '../chat'; +import { useScrollStatus } from '../scrollStatus'; function blockJs(ms: number) { const end = Date.now() + ms; @@ -57,6 +58,7 @@ const toast = (message: string) => { export default function ChatScreen() { const ref = useRef(null); + const [scrolled, track] = useScrollStatus(); const [dark, setDark] = useState(false); const [mounted, setMounted] = useState(true); const [refreshing, setRefreshing] = useState(false); @@ -121,11 +123,20 @@ export default function ChatScreen() { onPress={() => setList((s) => ({ ...s, chats: s.chats.slice(1) }))} />