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
5 changes: 5 additions & 0 deletions android/src/main/java/me/sectiontn/flume/FlumeRecyclerView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,11 @@ class FlumeRecyclerView(context: 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)
Expand Down
8 changes: 8 additions & 0 deletions android/src/main/java/me/sectiontn/flume/FlumeView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -777,6 +777,14 @@ class FlumeView(context: Context) : FrameLayout(context) {
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)
}
Expand Down
4 changes: 4 additions & 0 deletions android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,10 @@ class FlumeViewManager : ViewGroupManager<FlumeView>(), FlumeViewManagerInterfac
override fun scrollIndexIntoView(view: FlumeView, requestId: Int, index: Int, animated: Boolean, viewOffset: Double) =
view.scrollIndexIntoView(requestId, index, animated, viewOffset)

override fun scrollTo(view: FlumeView, x: Double, y: Double, animated: Boolean) = view.scrollToPoint(x, y, animated)

override fun flashScrollIndicators(view: FlumeView) = view.flashScrollIndicators()

override fun setNativeRefreshing(view: FlumeView, refreshing: Boolean) = view.setNativeRefreshing(refreshing)

companion object {
Expand Down
45 changes: 39 additions & 6 deletions example/src/screens/ScrollScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import { type FunctionComponent, useCallback, useMemo, useState } from 'react';
import { Button, Platform, Text, TextInput, ToastAndroid, View } from 'react-native';
import { type CellNode, cell, Flume, type FlumeProps } from 'react-native-flume';
import Animated, {
scrollTo,
useAnimatedRef,
useAnimatedScrollHandler,
useAnimatedStyle,
useSharedValue,
} from 'react-native-reanimated';
import { scheduleOnRN } from 'react-native-worklets';
import { scheduleOnRN, scheduleOnUI } from 'react-native-worklets';

type Row = { id: string; title: string; body: string };

Expand Down Expand Up @@ -50,6 +52,15 @@ const renderRow = (item: Row): CellNode => {
]);
};

// The same row as a column, for the horizontal list.
const renderColumn = (item: Row): CellNode => {
'worklet';
return cell.view({ width: 160, padding: 12, gap: 4 }, [
cell.text(item.title, { fontSize: 16, fontWeight: '600', color: '#111111' }),
cell.text(item.body, { fontSize: 13, color: '#555555' }),
]);
};

const toast = (message: string) => {
if (Platform.OS === 'android') ToastAndroid.show(message, ToastAndroid.SHORT);
};
Expand All @@ -61,7 +72,7 @@ const INSETS = { top: 40, bottom: 120 };

export default function ScrollScreen() {
const rows = useMemo(() => makeRows(), []);
const [status, setStatus] = useState({ offset: 0, first: -1 });
const [status, setStatus] = useState({ offset: 0, x: 0, first: -1 });
const [taps, setTaps] = useState(0);
const [dismiss, setDismiss] = useState(0);
const [insets, setInsets] = useState(false);
Expand All @@ -79,16 +90,28 @@ export default function ScrollScreen() {
}, []);
const offset = useSharedValue(0);
const reportOffset = useCallback(
(value: number) => setStatus((s) => ({ ...s, offset: value })),
(y: number, x: number) => setStatus((s) => ({ ...s, offset: y, x })),
[],
);
const onScroll = useAnimatedScrollHandler((e) => {
offset.value = e.contentOffset.y;
scheduleOnRN(reportOffset, Math.round(e.contentOffset.y));
scheduleOnRN(reportOffset, Math.round(e.contentOffset.y), Math.round(e.contentOffset.x));
});
const headerStyle = useAnimatedStyle(() => ({
transform: [{ translateY: -Math.min(Math.max(offset.value, 0), HEADER_HEIGHT) }],
}));
const [horizontal, setHorizontal] = useState(false);
const [inverted, setInverted] = useState(false);
// Reanimated's scrollTo runs on the UI runtime and reaches the list as ScrollView's command.
const listRef = useAnimatedRef();
const scrollTo400 = () => {
const x = horizontal ? 400 : 0;
const y = horizontal ? 0 : 400;
scheduleOnUI(() => {
'worklet';
scrollTo(listRef, x, y, true);
});
};
return (
<View style={{ flex: 1 }}>
<View
Expand All @@ -114,13 +137,20 @@ export default function ScrollScreen() {
<Button title={`Rate: ${fast ? 'fast' : 'normal'}`} onPress={() => setFast((v) => !v)} />
<Button title="Block JS 3 s" onPress={() => blockJs(3000)} />
<Button title="Refresh 1 s" onPress={refreshForASecond} />
<Button title="scrollTo 400" onPress={scrollTo400} />
<Button
title={horizontal ? 'Vertical' : 'Horizontal'}
onPress={() => setHorizontal((v) => !v)}
/>
<Button title={inverted ? 'Upright' : 'Inverted'} onPress={() => setInverted((v) => !v)} />
</View>
<TextInput
placeholder="Search"
style={{ marginHorizontal: 8, padding: 8, borderWidth: 1, borderColor: '#cccccc' }}
/>
<Text style={{ padding: 8 }} testID="scroll-status">
offset {status.offset} first viewable {status.first} pulls {pulls} pressed {pressed}
offset {status.offset} x {status.x} first viewable {status.first} pulls {pulls} pressed{' '}
{pressed}
</Text>
<View style={{ flex: 1, overflow: 'hidden' }}>
<Animated.View
Expand All @@ -144,9 +174,12 @@ export default function ScrollScreen() {
</Text>
</Animated.View>
<AnimatedFlume
ref={listRef}
horizontal={horizontal}
inverted={inverted}
data={rows}
keyExtractor={(r) => r.id}
renderCell={renderRow}
renderCell={horizontal ? renderColumn : renderRow}
contentContainerStyle={{ paddingTop: HEADER_HEIGHT }}
onPress={({ item, id }) => {
const message = id === 'like' ? `like ${item.title}` : item.title;
Expand Down
53 changes: 53 additions & 0 deletions example/src/types/refs.types.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Refs typed for FlatList, FlashList and LegendList fit Flume's ref prop, and Flume's own handle keeps its Promises.
import type { LegendListRef } from '@legendapp/list/react-native';
import type { FlashListRef } from '@shopify/flash-list';
import { useRef } from 'react';
import { type FlatList, Text } from 'react-native';
import { Flume, type FlumeRef } from 'react-native-flume';

type Item = { id: string; title: string };

const FIRST: Item = { id: 'a', title: 'First' };
const DATA: Item[] = [FIRST, { id: 'b', title: 'Second' }];

export function ForeignRefs() {
const flatList = useRef<FlatList<Item>>(null);
const untypedFlatList = useRef<FlatList>(null);
const flashList = useRef<FlashListRef<Item>>(null);
const legendList = useRef<LegendListRef>(null);
return (
<>
<Flume ref={flatList} data={DATA} renderItem={({ item }) => <Text>{item.title}</Text>} />
<Flume
ref={untypedFlatList}
data={DATA}
renderItem={({ item }) => (
// @ts-expect-error the item type comes from data, not from an untyped FlatList ref
<Text>{item.missing}</Text>
)}
/>
<Flume ref={flashList} data={DATA} renderItem={({ item }) => <Text>{item.title}</Text>} />
<Flume ref={legendList} data={DATA} renderItem={({ item }) => <Text>{item.title}</Text>} />
</>
);
}

export function FlumeRefs() {
const ref = useRef<FlumeRef<Item>>(null);
const plain = useRef<FlumeRef>(null);
const scroll = async () => {
await ref.current?.scrollToIndex({ index: 1 });
await ref.current?.scrollToItem({ item: FIRST });
await plain.current?.scrollToEnd();
};
return (
<>
<Flume
ref={ref}
data={DATA}
renderItem={({ item }) => <Text onPress={scroll}>{item.title}</Text>}
/>
<Flume ref={plain} data={DATA} renderItem={({ item }) => <Text>{item.title}</Text>} />
</>
);
}
33 changes: 26 additions & 7 deletions ios/FLMView.mm
Original file line number Diff line number Diff line change
Expand Up @@ -1549,11 +1549,24 @@ - (CGPoint)pointAt:(CGFloat)offset
return _horizontal ? CGPointMake(offset, current.y) : CGPointMake(current.x, offset);
}

// An earlier command's glide stops where it is, as Android stops its scroller, so it cannot carry the list past a new target.
- (void)stopGlide
{
if (!_gliding) {
return;
}
_gliding = NO;
_replacingGlide = YES;
[_collectionView setContentOffset:_collectionView.contentOffset animated:NO];
_replacingGlide = NO;
}

// React Native sends nothing for a move under half a point; an animated scroll's events come from its frames.
- (void)scrollTo:(CGFloat)offset animated:(BOOL)animated
{
// No animation will end, so no command waits to land again.
if (std::fabs(offset - [self currentOffset]) <= 0.5) {
[self stopGlide];
_pendingTarget.reset();
[self reclaimGlideSlots];
[self landCommand];
Expand Down Expand Up @@ -1940,6 +1953,18 @@ - (void)scrollToEnd:(NSInteger)requestId animated:(BOOL)animated
animated:animated];
}

// ScrollView's scrollTo carries no command id: it ends the command in flight, then moves along the list's axis.
- (void)scrollTo:(double)x y:(double)y animated:(BOOL)animated
{
[self endCommand];
[self scrollToOffset:0 offset:(_horizontal ? x : y) animated:animated];
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

- (void)flashScrollIndicators
{
[_collectionView flashScrollIndicators];
}

// 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
Expand Down Expand Up @@ -1970,13 +1995,7 @@ - (void)scrollIndexIntoView:(NSInteger)requestId
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 stopGlide];
[self landCommand];
return;
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"prepare": "bob build",
"lint": "biome check .",
"format": "biome check --write .",
"typecheck": "tsc",
"typecheck": "tsc && tsc -p tsconfig.legacy-types.json",
"bench": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON example/benchmark/run.mts",
"test": "vitest run",
"test:cpp": "scripts/test-cpp.sh",
Expand Down
45 changes: 38 additions & 7 deletions src/Flume.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,10 @@ import type {
CellRendererProps,
FlumeProps,
FlumeRef,
ListRef,
PressInfo,
ReactCell,
ScrollResponder,
SeparatorProps,
ViewToken,
} from './types';
Expand Down Expand Up @@ -523,6 +525,29 @@ function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
[commands],
);

// ScrollView's methods, for the scroll view refs FlashList and LegendList hand out and for getScrollResponder.
const responder = useMemo<ScrollResponder>(
() => ({
scrollTo: (params) => {
const native = nativeRef.current;
if (native === null) return;
// Native ends the command in flight, and a data commit must not send it again.
recent.current = null;
Commands.scrollTo(native, params?.x ?? 0, params?.y ?? 0, params?.animated ?? true);
},
scrollToEnd: (params) =>
sendCommand((native, id) => Commands.scrollToEnd(native, id, params?.animated ?? true)),
flashScrollIndicators: () => {
if (nativeRef.current !== null) Commands.flashScrollIndicators(nativeRef.current);
},
getScrollableNode: () => nativeRef.current,
getNativeScrollRef: () => nativeRef.current,
}),
[sendCommand],
);
useImperativeHandle(props.scrollViewRef, () => responder, [responder]);
useImperativeHandle(props.refScrollView, () => responder, [responder]);

// FlatList's defaults: animated, the item at the start edge; native clamps the index.
useImperativeHandle(ref, () => {
const toIndex = (
Expand Down Expand Up @@ -554,8 +579,7 @@ function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
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)),
scrollToEnd: responder.scrollToEnd,
scrollToItem: ({ item, animated = true, viewPosition = 0, viewOffset = 0 }) =>
found(item, (index) => toIndex(index, animated, viewPosition, viewOffset, 'scrollToItem')),
scrollToTop: (params) =>
Expand All @@ -567,10 +591,13 @@ function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
scrollItemIntoView: ({ item, animated = true, viewOffset = 0 }) =>
found(item, (index) => intoView(index, animated, viewOffset, 'scrollItemIntoView')),
setNativeProps: (nativeProps) => nativeRef.current?.setNativeProps(nativeProps),
flashScrollIndicators: responder.flashScrollIndicators,
getScrollResponder: () => responder,
getNativeScrollRef: () => nativeRef.current,
getScrollableNode: () => nativeRef.current,
getAnimatableRef: () => nativeRef.current,
};
}, [sendCommand]);
}, [sendCommand, responder]);

const press = (handler: ((info: PressInfo<T>) => void) | undefined) =>
handler === undefined
Expand Down Expand Up @@ -643,7 +670,11 @@ function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
);
}

// forwardRef drops the generic; the cast gives callers the item type back.
export const Flume = forwardRef(FlumeInner) as <T>(
props: FlumeProps<T> & { ref?: Ref<FlumeRef> },
) => ReactElement;
// forwardRef drops the generic, so the cast gives callers the item type back. The ref prop takes a ref typed for
// FlatList, FlashList or LegendList through the first signature, and ComponentRef reads Flume's handle from the last.
type FlumeComponent = {
<T>(props: FlumeProps<T> & { ref?: Ref<ListRef<NoInfer<T>>> }): ReactElement;
<T>(props: FlumeProps<T> & { ref?: Ref<FlumeRef<NoInfer<T>>> }): ReactElement;
};

export const Flume = forwardRef(FlumeInner) as FlumeComponent;
Loading
Loading