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
7 changes: 7 additions & 0 deletions ios/FLMView.mm
Original file line number Diff line number Diff line change
Expand Up @@ -1394,8 +1394,12 @@ - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
_scrollEvents.didEndDragging(decelerate);
// The finger had the list, so no realign pulls it back to a jump's target, as a drag drops it on Android.
_realign.reset();
if (!decelerate) {
[self writeShadowOrigins];
// A command that landed under the finger ends here, since no layout follows a release without momentum.
[self settleCommand];
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

Expand All @@ -1408,6 +1412,9 @@ - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self emitScrollEvents:_scrollEvents.didEndDecelerating() velocity:CGPointZero];
[self writeShadowOrigins];
// No layout follows the end of momentum, so a realign resumes and the command in flight ends here, as on Android.
[self realignIfIdle];
[self settleCommand];
}

// Rows measured during the glide can move the target, so an animated command lands on it again.
Expand Down
100 changes: 72 additions & 28 deletions src/Flume.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
import { type StyleProp, View, type ViewStyle } from 'react-native';
import { createSerializable } from 'react-native-worklets';
import { cellKinds, itemComponentCell, type ResolvedCell, resolveCell } from './cells';
import { createScrollCommands } from './commands';
import { type DataState, diffData, itemOf, type NativeItems, typeOf } from './data';
import { FlumeSlot } from './FlumeSlot';
import { hostProps } from './foreign';
Expand Down Expand Up @@ -60,6 +61,15 @@ import type {
ViewToken,
} from './types';

type NativeView = ComponentRef<typeof FlumeViewNativeComponent>;
type RecentCommand = {
send: (native: NativeView, id: number) => void;
index?: number;
id: number;
// Native ended it (a drag, a newer command), so data of the same frame no longer sends it again.
ended: boolean;
};

// FlatList's rule for the list components: an element renders as given, a component through createElement.
// A given style wraps it in a View, as FlatList and FlashList do.
function componentElement(
Expand Down Expand Up @@ -125,9 +135,11 @@ function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
const released = useRef(false);
const prev = useRef<{ storeId: number; signature?: string; state?: DataState<T> }>({ storeId });
const warned = useRef({ duplicates: false, messages: new Set<string>() });
const nativeRef = useRef<ComponentRef<typeof FlumeViewNativeComponent>>(null);
// Native reports the end of a scroll command by this id, which only grows.
const commandId = useRef(0);
const nativeRef = useRef<NativeView>(null);
// Native reports the end of each scroll command by its id, which settles the command's Promise.
const [commands] = useState(createScrollCommands);
// The last scroll command until the next frame, sent again after data committed meanwhile.
const recent = useRef<RecentCommand | null>(null);
// React Native's RefreshControl rule: a pull starts native refreshing, so an unchanged prop is sent back.
const wantsRefreshing = refresh.refreshing;
const nativeRefreshing = useRef(wantsRefreshing);
Expand Down Expand Up @@ -289,7 +301,14 @@ function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
commit.diffMs,
performance.now() - start,
);
}, [host, storeId, commit, report]);
// A scroll from this frame reached native before this data, so it goes again to land in the new rows.
const command = recent.current;
const native = nativeRef.current;
if (command !== null && native !== null && !command.ended) {
command.id = commands.move();
command.send(native, command.id);
}
}, [host, storeId, commit, report, commands]);

useLayoutEffect(() => {
const sent = sentSticky.current;
Expand Down Expand Up @@ -456,38 +475,62 @@ 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> => {
const native = nativeRef.current;
if (native === null) return Promise.resolve();
const { id, done } = commands.start();
send(native, id);
const command: RecentCommand = { send, index, id, ended: false };
recent.current = command;
requestAnimationFrame(() => {
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`);
}
});
return done;
},
[commands, warn],
);
const endCommand = useCallback(
(event: { nativeEvent: { id: number } }) => {
const { id } = event.nativeEvent;
const command = recent.current;
if (command !== null && command.id <= id) command.ended = true;
commands.endThrough(id);
},
[commands],
);
// StrictMode replays this effect, so the tracker keeps working after endAll.
useEffect(
() => () => {
recent.current = null;
commands.endAll();
},
[commands],
);

// FlatList's defaults: animated, the item at the start edge; native clamps the index.
useImperativeHandle(
ref,
() => ({
scrollToIndex: ({ index, animated = true, viewPosition = 0, viewOffset = 0 }) => {
const native = nativeRef.current;
if (native === null) return;
if (index < 0 || index >= count.current) {
warn(`scrollToIndex: index ${index} is out of range for ${count.current} items`);
}
Commands.scrollToIndex(
native,
++commandId.current,
scrollToIndex: ({ index, animated = true, viewPosition = 0, viewOffset = 0 }) =>
sendCommand(
(native, id) =>
Commands.scrollToIndex(native, id, index, animated, viewPosition, viewOffset),
index,
animated,
viewPosition,
viewOffset,
);
},
scrollToOffset: ({ offset, animated = true }) => {
const native = nativeRef.current;
if (native !== null) Commands.scrollToOffset(native, ++commandId.current, offset, animated);
},
scrollToEnd: (params) => {
const native = nativeRef.current;
if (native !== null)
Commands.scrollToEnd(native, ++commandId.current, params?.animated ?? true);
},
),
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)),
getScrollableNode: () => nativeRef.current,
getAnimatableRef: () => nativeRef.current,
}),
[warn],
[sendCommand],
);

const press = (handler: ((info: PressInfo<T>) => void) | undefined) =>
Expand Down Expand Up @@ -520,6 +563,7 @@ function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
{...hostProps(given)}
{...nativeProps(props, warn)}
ref={nativeRef}
onScrollCommandEnd={endCommand}
storeId={storeId}
itemAnimations={itemAnimations}
onCellPress={press(onPress)}
Expand Down
179 changes: 179 additions & 0 deletions src/__tests__/Flume.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -836,8 +836,187 @@ describe('Flume edges', () => {
});

describe('Flume ref', () => {
const frames: Array<() => void> = [];
const nextFrame = () => {
for (const run of frames.splice(0)) run();
};
const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
const track = (done: Promise<void> | undefined) => {
const state = { resolved: false };
void done?.then(() => {
state.resolved = true;
});
return state;
};
const endCommand = (tree: ReactTestRenderer, id: number) =>
act(() => {
tree.root
.find((node) => String(node.type) === 'FlumeView')
.props.onScrollCommandEnd({ nativeEvent: { id } });
});

beforeEach(() => {
vi.resetModules();
frames.length = 0;
vi.stubGlobal('requestAnimationFrame', (run: () => void) => frames.push(run));
});

it('scrollToIndex resolves when native reports its end', async () => {
installHost();
const { Flume } = await import('../Flume');
const ref = createRef<FlumeRef>();
const tree = await mount(createElement(Flume, { ref, data: [item], renderCell }));
const state = track(ref.current?.scrollToIndex({ index: 0 }));
await flush();
expect(state.resolved).toBe(false);
await endCommand(tree, 1);
await flush();
expect(state.resolved).toBe(true);
});

it('resolves at once without a native view', async () => {
installHost();
const { Flume } = await import('../Flume');
const { Commands } = await import('../specs/FlumeViewNativeComponent');
const ref = createRef<FlumeRef>();
await act(async () => {
create(createElement(Flume, { ref, data: [item], renderCell }), {
createNodeMock: () => null,
});
});
const state = track(ref.current?.scrollToOffset({ offset: 10 }));
await flush();
expect(state.resolved).toBe(true);
expect(Commands.scrollToOffset).not.toHaveBeenCalled();
});

it('resolves pending scrolls on unmount', async () => {
installHost();
const { Flume } = await import('../Flume');
const ref = createRef<FlumeRef>();
const tree = await mount(createElement(Flume, { ref, data: [item], renderCell }));
const state = track(ref.current?.scrollToEnd());
await act(async () => tree.unmount());
await flush();
expect(state.resolved).toBe(true);
});

it('sends a command again under a new id after data of the same frame', async () => {
const host = installHost();
const { Flume } = await import('../Flume');
const { Commands } = await import('../specs/FlumeViewNativeComponent');
vi.mocked(Commands.scrollToIndex).mockImplementation((_view, id) => {
host.log.push(`index ${id}`);
});
const ref = createRef<FlumeRef>();
const tree = await mount(createElement(Flume, { ref, data: [item], renderCell }));
ref.current?.scrollToIndex({ index: 1, animated: false });
await act(async () =>
tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })),
);
expect(host.log.slice(-3)).toEqual(['index 1', 'data [1]', 'index 2']);
expect(Commands.scrollToIndex).toHaveBeenLastCalledWith(expect.anything(), 2, 1, false, 0, 0);
});

it('keeps a scroll sent again pending until its new id ends', async () => {
installHost();
const { Flume } = await import('../Flume');
const ref = createRef<FlumeRef>();
const tree = await mount(createElement(Flume, { ref, data: [item], renderCell }));
const state = track(ref.current?.scrollToIndex({ index: 1 }));
await act(async () =>
tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })),
);
await endCommand(tree, 1);
await flush();
expect(state.resolved).toBe(false);
await endCommand(tree, 2);
await flush();
expect(state.resolved).toBe(true);
});

it('does not send a scroll again once native ended it', async () => {
installHost();
const { Flume } = await import('../Flume');
const { Commands } = await import('../specs/FlumeViewNativeComponent');
const ref = createRef<FlumeRef>();
const tree = await mount(createElement(Flume, { ref, data: [item], renderCell }));
ref.current?.scrollToEnd();
await endCommand(tree, 1);
await act(async () =>
tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })),
);
expect(Commands.scrollToEnd).toHaveBeenCalledTimes(1);
});

it('sends a scroll again when only an older command ended', async () => {
installHost();
const { Flume } = await import('../Flume');
const { Commands } = await import('../specs/FlumeViewNativeComponent');
const ref = createRef<FlumeRef>();
const tree = await mount(createElement(Flume, { ref, data: [item], renderCell }));
ref.current?.scrollToOffset({ offset: 10 });
ref.current?.scrollToEnd();
await endCommand(tree, 1);
await act(async () =>
tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })),
);
expect(Commands.scrollToEnd).toHaveBeenCalledTimes(2);
});

it('does not send a scroll again once its frame passed', async () => {
installHost();
const { Flume } = await import('../Flume');
const { Commands } = await import('../specs/FlumeViewNativeComponent');
const ref = createRef<FlumeRef>();
const tree = await mount(createElement(Flume, { ref, data: [item], renderCell }));
ref.current?.scrollToEnd();
nextFrame();
await act(async () =>
tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })),
);
expect(Commands.scrollToEnd).toHaveBeenCalledTimes(1);
});

it('does not send a scroll again when native data is unchanged', async () => {
installHost();
const { Flume } = await import('../Flume');
const { Commands } = await import('../specs/FlumeViewNativeComponent');
const ref = createRef<FlumeRef>();
const tree = await mount(createElement(Flume, { ref, data: [item], renderCell }));
ref.current?.scrollToOffset({ offset: 10 });
await act(async () => tree.update(createElement(Flume, { ref, data: [item], renderCell })));
expect(Commands.scrollToOffset).toHaveBeenCalledTimes(1);
});

it('checks an index against the data of the same frame', async () => {
installHost();
const { Flume } = await import('../Flume');
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const ref = createRef<FlumeRef>();
const tree = await mount(createElement(Flume, { ref, data: [item], renderCell }));
ref.current?.scrollToIndex({ index: 1 });
await act(async () =>
tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })),
);
nextFrame();
expect(warn).not.toHaveBeenCalled();
warn.mockRestore();
});

it('warns about an index past the data once its frame passes', async () => {
installHost();
const { Flume } = await import('../Flume');
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const ref = createRef<FlumeRef>();
await mount(createElement(Flume, { ref, data: [item], renderCell }));
ref.current?.scrollToIndex({ index: 5 });
expect(warn).not.toHaveBeenCalled();
nextFrame();
expect(warn).toHaveBeenCalledWith(
'react-native-flume: scrollToIndex: index 5 is out of range for 1 items',
);
warn.mockRestore();
});

it('sends the commands with FlatList defaults and a growing id', async () => {
Expand Down
Loading
Loading