Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions android/src/main/java/me/sectiontn/flume/FlumeView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,30 @@ class FlumeView(context: Context) : FrameLayout(context) {
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 lastVisible = maxOf(layoutManager.findFirstVisibleItemPosition(), layoutManager.findLastVisibleItemPosition())
val viewPosition = when {
position == null || target.waitsForData(rows) -> 1f
else -> IntoView.target(position, minOf(first, last), maxOf(first, last), lastVisible)
}
if (viewPosition == null) {
// As any new scroll does: an earlier command's realign or glide must not move the row back out.
pendingAlign = null
jumps.cancel()?.let { dropJump(it) }
forgetLanding()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
recycler.stopScroll()
landCommand()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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 requestJump(target: JumpTarget, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) {
jumps.cancel()?.let { dropJump(it) }
Expand Down
3 changes: 3 additions & 0 deletions android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,9 @@ class FlumeViewManager : ViewGroupManager<FlumeView>(), FlumeViewManagerInterfac

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 setNativeRefreshing(view: FlumeView, refreshing: Boolean) = view.setNativeRefreshing(refreshing)

companion object {
Expand Down
10 changes: 10 additions & 0 deletions android/src/main/java/me/sectiontn/flume/ScrollCommands.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,13 @@ class ScrollCommands {
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, lastVisible: Int = -1): Float? = when {
firstFull < 0 || lastFull < firstFull -> if (lastVisible >= 0 && position > lastVisible) 1f else 0f
position < firstFull -> 0f
position > lastFull -> 1f
else -> null
}
}
26 changes: 26 additions & 0 deletions android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package me.sectiontn.flume

import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test

class ScrollCommandsTest {
Expand Down Expand Up @@ -80,4 +81,29 @@ class ScrollCommandsTest {
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))
}

@Test
fun intoViewAlignsTheEndOfARowBelowTheRowsPartlyInViewWhenNoneIsFullyInView() {
assertEquals(1f, IntoView.target(1, -1, -1, 0))
assertEquals(0f, IntoView.target(0, -1, -1, 0))
assertEquals(0f, IntoView.target(4, -1, -1, -1))
}
}
11 changes: 11 additions & 0 deletions cpp/adapter/ScrollCommands.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,14 @@ void ScrollCommands::reset() {
}

} // namespace flume

namespace flume {

std::optional<float> intoViewPosition(int position, int firstFull, int lastFull, int lastVisible) {
if (firstFull < 0 || lastFull < firstFull) return lastVisible >= 0 && position > lastVisible ? 1.f : 0.f;
if (position < firstFull) return 0.f;
if (position > lastFull) return 1.f;
return std::nullopt;
}

} // namespace flume
5 changes: 5 additions & 0 deletions cpp/adapter/ScrollCommands.h
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
#pragma once

#include <cstdint>
#include <optional>

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, a row after the last one partly in view goes to the end, others to the start.
std::optional<float> intoViewPosition(int position, int firstFull, int lastFull, int lastVisible = -1);

// The scroll command in flight: its id is reported once, when it settles at rest or is interrupted.
class ScrollCommands {
public:
Expand Down
21 changes: 21 additions & 0 deletions cpp/tests/scroll_commands_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,24 @@ TEST_CASE("ScrollCommands a newer command clears the landed mark") {
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("IntoView aligns the end of a row below the rows partly in view when none is fully in view") {
CHECK(intoViewPosition(1, -1, -1, 0) == 1.f);
CHECK(intoViewPosition(0, -1, -1, 0) == 0.f);
CHECK(intoViewPosition(4, -1, -1, -1) == 0.f);
}
44 changes: 44 additions & 0 deletions ios/FLMView.mm
Original file line number Diff line number Diff line change
Expand Up @@ -1940,6 +1940,50 @@ - (void)scrollToEnd:(NSInteger)requestId animated:(BOOL)animated
animated:animated];
}

// A row already fully in view ends the command where the list is. An index past the data lands at the end edge.
- (void)scrollIndexIntoView:(NSInteger)requestId
index:(NSInteger)index
animated:(BOOL)animated
viewOffset:(double)viewOffset
{
[self beginCommand:requestId];
if (!_attached) {
[self landCommand];
return;
}
std::optional<float> viewPosition = 1;
if (_rows.dataCount > 0 && index < _rows.dataCount) {
const FLMViewport viewport = [_layout viewportFor:_collectionView.bounds];
int firstFull = INT_MAX;
int lastFull = -1;
int lastVisible = -1;
for (const flume::ItemSpan &span : [_layout spansIn:viewport]) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
lastVisible = std::max(lastVisible, span.index);
if (span.start >= -0.5f && span.end <= viewport.length + 0.5f) {
firstFull = std::min(firstFull, span.index);
lastFull = std::max(lastFull, span.index);
}
}
const int position = _rows.position(*flume::clampIndex(static_cast<int>(index), _rows.dataCount));
viewPosition = flume::intoViewPosition(position, lastFull < 0 ? -1 : firstFull, lastFull, lastVisible);
}
if (!viewPosition) {
[self dropJump];
_pendingTarget.reset();
// An earlier command's glide stops where it is, as on Android, so it cannot carry the row back out.
if (_gliding) {
_gliding = NO;
_replacingGlide = YES;
[_collectionView setContentOffset:_collectionView.contentOffset animated:NO];
_replacingGlide = NO;
}
[self landCommand];
return;
}
[self scrollToTarget:FLMPendingTarget{FLMPendingTarget::Kind::Index, static_cast<int>(index), *viewPosition, viewOffset}
animated:animated];
}

- (void)setNativeRefreshing:(BOOL)refreshing
{
[_refresh setRefreshing:refreshing];
Expand Down
65 changes: 52 additions & 13 deletions src/Flume.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { createScrollCommands } from './commands';
import { type DataState, diffData, itemOf, type NativeItems, typeOf } from './data';
import { FlumeSlot } from './FlumeSlot';
import { hostProps } from './foreign';
import { useKeyboardEvent } from './keyboard';
import {
contentPadding,
gapsOf,
Expand Down Expand Up @@ -123,6 +124,10 @@ function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
onStartReached,
keyboardShouldPersistTaps,
} = props;
useKeyboardEvent('keyboardWillShow', props.onKeyboardWillShow);
useKeyboardEvent('keyboardWillHide', props.onKeyboardWillHide);
useKeyboardEvent('keyboardDidShow', props.onKeyboardDidShow);
useKeyboardEvent('keyboardDidHide', props.onKeyboardDidHide);
const refresh = refreshOf(props);
const { onRefresh } = refresh;
const host = getHost();
Expand Down Expand Up @@ -159,6 +164,11 @@ function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
count.current = data.length;
const dataRef = useRef<readonly unknown[]>(data);
dataRef.current = data;
// The data of the last commit, which native shows: a render React throws away never reaches it.
const shownData = useRef<readonly unknown[]>(data);
useLayoutEffect(() => {
shownData.current = data;
}, [data]);
// The keys separators.highlight reads when called, so the row before is the latest one.
const separatorKeys = useRef<{ keys: readonly string[]; index: ReadonlyMap<string, number> }>({
keys: [],
Expand Down Expand Up @@ -477,7 +487,7 @@ function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {

// The index is checked once the frame ends, against the data a handler committed with the scroll.
const sendCommand = useCallback(
(send: RecentCommand['send'], index?: number): Promise<void> => {
(send: RecentCommand['send'], index?: number, method = 'scrollToIndex'): Promise<void> => {
const native = nativeRef.current;
if (native === null) return Promise.resolve();
const { id, done } = commands.start();
Expand All @@ -488,7 +498,7 @@ function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
if (recent.current !== command) return;
recent.current = null;
if (index !== undefined && (index < 0 || index >= count.current)) {
warn(`scrollToIndex: index ${index} is out of range for ${count.current} items`);
warn(`${method}: index ${index} is out of range for ${count.current} items`);
}
});
return done;
Expand All @@ -514,24 +524,53 @@ function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
);

// FlatList's defaults: animated, the item at the start edge; native clamps the index.
useImperativeHandle(
ref,
() => ({
useImperativeHandle(ref, () => {
const toIndex = (
index: number,
animated: boolean,
viewPosition: number,
viewOffset: number,
method?: string,
) =>
sendCommand(
(native, id) =>
Commands.scrollToIndex(native, id, index, animated, viewPosition, viewOffset),
index,
method,
);
const intoView = (index: number, animated: boolean, viewOffset: number, method: string) =>
sendCommand(
(native, id) => Commands.scrollIndexIntoView(native, id, index, animated, viewOffset),
index,
method,
);
// FlatList finds the item by identity in the data it shows, its committed props.
const found = (item: unknown, scroll: (index: number) => Promise<void>) => {
const index = shownData.current.indexOf(item);
return index < 0 ? Promise.resolve() : scroll(index);
};
return {
scrollToIndex: ({ index, animated = true, viewPosition = 0, viewOffset = 0 }) =>
sendCommand(
(native, id) =>
Commands.scrollToIndex(native, id, index, animated, viewPosition, viewOffset),
index,
),
toIndex(index, animated, viewPosition, viewOffset),
scrollToOffset: ({ offset, animated = true }) =>
sendCommand((native, id) => Commands.scrollToOffset(native, id, offset, animated)),
scrollToEnd: (params) =>
sendCommand((native, id) => Commands.scrollToEnd(native, id, params?.animated ?? true)),
scrollToItem: ({ item, animated = true, viewPosition = 0, viewOffset = 0 }) =>
found(item, (index) => toIndex(index, animated, viewPosition, viewOffset, 'scrollToItem')),
scrollToTop: (params) =>
sendCommand((native, id) =>
Commands.scrollToOffset(native, id, 0, params?.animated ?? true),
),
scrollIndexIntoView: ({ index, animated = true, viewOffset = 0 }) =>
intoView(index, animated, viewOffset, 'scrollIndexIntoView'),
scrollItemIntoView: ({ item, animated = true, viewOffset = 0 }) =>
found(item, (index) => intoView(index, animated, viewOffset, 'scrollItemIntoView')),
setNativeProps: (nativeProps) => nativeRef.current?.setNativeProps(nativeProps),
getScrollableNode: () => nativeRef.current,
getAnimatableRef: () => nativeRef.current,
}),
[sendCommand],
);
};
}, [sendCommand]);

const press = (handler: ((info: PressInfo<T>) => void) | undefined) =>
handler === undefined
Expand Down
Loading
Loading