Skip to content
Open
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## 2.0.17
- Feat: Add Reanimated onScroll handler executed on the UI thread

## 2.0.16
- Feat: Add KeyboardAvoidingLegendList component for better keyboard handling integration
- Fix: Stale containers are not being removed and overlap with new data when using getItemType #335
Expand Down
4 changes: 4 additions & 0 deletions example/app/(tabs)/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,10 @@ const data: ListElement[] = [
title: "Accurate scrollToHuge",
url: "/accurate-scrollto-huge",
},
{
title: "Reanimated scroll state on UI",
url: "/reanimated-scroll-state",
},
].map(
(v, i) =>
({
Expand Down
143 changes: 143 additions & 0 deletions example/app/reanimated-scroll-state/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { useCallback, useState } from "react";
import { Pressable, SafeAreaView, StatusBar, StyleSheet, Text, View } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { useAnimatedScrollHandler, useSharedValue } from "react-native-reanimated";

import { AnimatedLegendList } from "@legendapp/list/reanimated";
import type { LegendListRenderItemProps } from "@/types";
import { countries, getEmojiFlag, type TCountryCode } from "countries-list";

type Country = {
id: string;
name: string;
flag: string;
};

const DATA: Country[] = Object.entries(countries)
.map(([code, country]) => ({
flag: getEmojiFlag(code as TCountryCode),
id: code,
name: country.name,
}))
.sort((a, b) => a.name.localeCompare(b.name));

type ItemProps = {
item: Country;
onPress: () => void;
isSelected: boolean;
};

const Item = ({ item, onPress, isSelected }: ItemProps) => (
<Pressable
onPress={onPress}
style={({ pressed }) => [styles.item, isSelected && styles.selectedItem, pressed && styles.pressedItem]}
>
<View style={styles.flagContainer}>
<Text style={styles.flag}>{item.flag}</Text>
</View>
<View style={styles.contentContainer}>
<Text style={[styles.title, isSelected && styles.selectedText]}>
{item.name}
<Text style={styles.countryCode}> ({item.id})</Text>
</Text>
</View>
</Pressable>
);

const App = () => {
const [selectedId, setSelectedId] = useState<string>();

const scrollY = useSharedValue(0);

const onScroll = useAnimatedScrollHandler({
onScroll: (event) => {
console.log("onScroll", event);

scrollY.value = event.contentOffset.y;
},
});

const tapGesture = Gesture.Tap().onStart(({ absoluteY }) => {
"worklet";
const adjustedY = absoluteY + scrollY.value;
console.log("📍 Tap at scroll-adjusted Y:", adjustedY);
});

const keyExtractor = useCallback((item: Country) => item.id, []);

const renderItem = useCallback(
({ item }: LegendListRenderItemProps<Country>) => {
const isSelected = item.id === selectedId;

return <Item isSelected={isSelected} item={item} onPress={() => setSelectedId(item.id)} />;
},
[selectedId],
);

return (
<SafeAreaView style={styles.container}>
<GestureDetector gesture={tapGesture}>
<AnimatedLegendList
data={DATA}
estimatedItemSize={70}
extraData={selectedId}
keyExtractor={keyExtractor}
onScroll={onScroll}
recycleItems
renderItem={renderItem}
scrollEventThrottle={16}
/>
</GestureDetector>
</SafeAreaView>
);
};

export default App;

const styles = StyleSheet.create({
container: {
backgroundColor: "#f5f5f5",
flex: 1,
marginTop: StatusBar.currentHeight || 0,
},
contentContainer: {
flex: 1,
justifyContent: "center",
},
countryCode: {
color: "#666",
fontSize: 14,
fontWeight: "400",
},
flag: {
fontSize: 28,
},
flagContainer: {
alignItems: "center",
backgroundColor: "#f8f9fa",
borderRadius: 20,
height: 40,
justifyContent: "center",
marginRight: 16,
width: 40,
},
item: {
alignItems: "center",
backgroundColor: "#fff",
borderRadius: 12,
flexDirection: "row",
paddingHorizontal: 16,
paddingVertical: 6,
},
pressedItem: {},
selectedItem: {},
selectedText: {
color: "#1976d2",
fontWeight: "600",
},
title: {
color: "#333",
fontSize: 16,
fontWeight: "500",
},
});
32 changes: 28 additions & 4 deletions src/integrations/reanimated.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import * as React from "react";
import { type ComponentProps, memo, useCallback } from "react";
import type { NativeScrollEvent, NativeSyntheticEvent } from "react-native";
import type { SharedValue } from "react-native-reanimated";
import Animated from "react-native-reanimated";

import {
Expand All @@ -10,6 +12,7 @@ import {
type TypedMemo,
} from "@legendapp/list";
import { useCombinedRef } from "@/hooks/useCombinedRef";
import { isReanimatedScroll } from "@/utils/helpers";

type KeysToOmit =
| "getEstimatedItemSize"
Expand All @@ -20,12 +23,17 @@ type KeysToOmit =
| "renderItem"
| "onItemSizeChanged"
| "itemsAreEqual"
| "ItemSeparatorComponent";
| "ItemSeparatorComponent"
| "onScroll";

type PropsBase<ItemT> = LegendListPropsBase<ItemT, ComponentProps<typeof Animated.ScrollView>>;

type ReanimatedScrollHandler = | ((event: NativeSyntheticEvent<NativeScrollEvent>) => void)
| SharedValue<((event: NativeSyntheticEvent<NativeScrollEvent>) => void) | undefined>;

export interface AnimatedLegendListPropsBase<ItemT> extends Omit<PropsBase<ItemT>, KeysToOmit> {
refScrollView?: React.Ref<Animated.ScrollView>;
onScroll?: ReanimatedScrollHandler;
}

type OtherAnimatedLegendListProps<ItemT> = Pick<PropsBase<ItemT>, KeysToOmit>;
Expand All @@ -35,10 +43,13 @@ const typedMemo = memo as TypedMemo;
// A component that receives a ref for the Animated.ScrollView and passes it to the LegendList
const LegendListForwardedRef = typedMemo(
React.forwardRef(function LegendListForwardedRef<ItemT>(
props: LegendListProps<ItemT> & { refLegendList: (r: LegendListRef | null) => void },
props: LegendListProps<ItemT> & {
refLegendList: (r: LegendListRef | null) => void;
onScroll?: ReanimatedScrollHandler;
},
ref: React.Ref<Animated.ScrollView>,
) {
const { refLegendList, ...rest } = props;
const { refLegendList, onScroll, ...rest } = props;

const refFn = useCallback(
(r: LegendListRef) => {
Expand All @@ -47,7 +58,20 @@ const LegendListForwardedRef = typedMemo(
[refLegendList],
);

return <LegendList ref={refFn} refScrollView={ref} {...rest} />;
const scrollHandler = useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
if (onScroll) {
if (isReanimatedScroll(onScroll)) {
onScroll.value?.(event);
} else {
onScroll(event);
}
}
},
[onScroll],
);

return <LegendList onScroll={scrollHandler} ref={refFn} refScrollView={ref} {...rest} />;
}),
);

Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -697,4 +697,4 @@ export interface ScrollIndexWithOffsetPosition extends ScrollIndexWithOffset {
}

export type GetRenderedItemResult<ItemT> = { index: number; item: ItemT; renderedItem: React.ReactNode };
export type GetRenderedItem = (key: string) => GetRenderedItemResult<any> | null;
export type GetRenderedItem = (key: string) => GetRenderedItemResult<any> | null;
13 changes: 12 additions & 1 deletion src/utils/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
import type { ViewStyle } from "react-native";
import type { NativeScrollEvent, NativeSyntheticEvent, ViewStyle } from "react-native";
import type { SharedValue } from "react-native-reanimated";

type ScrollHandler = (e: NativeSyntheticEvent<NativeScrollEvent>) => void;

export function isReanimatedScroll(value: unknown): value is SharedValue<ScrollHandler | undefined> {
if (typeof value === "object" && value !== null && "value" in value) {
const val = (value as { value: unknown }).value;
return typeof val === "function" || val === undefined;
}
return false;
}

export function isFunction(obj: unknown): obj is (...args: any[]) => any {
return typeof obj === "function";
Expand Down