Look at my code: import MaterialCommunityIcons from…
- User
Look at my code: import MaterialCommunityIcons from '@expo/vector-icons/MaterialCommunityIcons'; import { LegendList } from '@legendapp/list'; import { useContext, useMemo, useState } from 'react'; import { View } from 'react-native'; import Animated, { withTiming, LinearTransition, Easing, EntryAnimationsValues, ExitAnimationsValues, LayoutAnimation, useAnimatedStyle, } from 'react-native-reanimated';
import { Category, Record, RecordType } from '@/src/types/model.types'; import { MainContext } from '@components/context'; import { Box, HStack } from '@components/ui/gluestack'; import { Text, TouchableRipple } from '@components/ui/react-native-paper';
const ANIMATION_DURATION = 300;
const expand = (values: EntryAnimationsValues): LayoutAnimation => { 'worklet'; return { initialValues: { height: 0, opacity: 0, }, animations: { height: withTiming(values.targetHeight, { duration: ANIMATION_DURATION }), opacity: withTiming(1, { duration: ANIMATION_DURATION }), }, }; };
const collapse = (values: ExitAnimationsValues): LayoutAnimation => { 'worklet'; return { initialValues: { height: values.currentHeight, opacity: 1, }, animations: { height: withTiming(0, { duration: ANIMATION_DURATION }), opacity: withTiming(0, { duration: ANIMATION_DURATION }), }, }; };
const AnimatedChevron: React.FC<{ isExpanded: boolean }> = ({ isExpanded }) => { const animatedStyle = useAnimatedStyle(() => { return { transform: [ { rotate: withTiming(isExpanded ? '-180deg' : '0deg', { duration: ANIMATION_DURATION, }), }, ], }; });
return ( <Animated.View style={animatedStyle}> </Animated.View> ); };
AnimatedChevron.displayName = 'AnimatedChevron';
interface BalanceTransactionsByCategoryProps { income: number; expenses: number; recordType: RecordType; records: Record[]; }
export const BalanceTransactionsByCategory: React.FC< BalanceTransactionsByCategoryProps
= ({ records, income, expenses, recordType }) => { const { categoriesMap } = useContext(MainContext); const [expandedCategoryIds, setExpandedCategoryIds] = useState( new Set(), );
const listData = useMemo(() => { const grouped = records.reduce((acc, record) => { if (record.transfer_id || record.type !== recordType) { return acc; } const categoryId = record.category_id!.toString(); const entry = acc.get(categoryId); if (entry) { entry.balance += record.value; entry.records.push(record); } else { acc.set(categoryId, { category: categoriesMap[categoryId], balance: record.value, records: [record], }); } return acc; }, new Map<string, { category: Category; balance: number; records: Record[] }>());
return Array.from(grouped.values()) .sort((a, b) => b.balance - a.balance) .flatMap((cat) => { const categoryItem = { type: 'category' as const, category: cat.category, balance: cat.balance, }; const recordItems = cat.records.map((record) => ({ type: 'record' as const, record, category: cat.category, })); return [categoryItem, ...recordItems]; });}, [records, categoriesMap, recordType]);
const toggleCategory = (categoryId: string) => { setExpandedCategoryIds((prevSet) => { const newSet = new Set(prevSet); if (newSet.has(categoryId)) { newSet.delete(categoryId); } else { newSet.add(categoryId); } return newSet; }); };
return ( <View style={{ flex: 1 }}> <LegendList data={listData} keyExtractor={(item) => item.type === 'category' ?
cat-${item.category.id}:rec-${item.record.id}} renderItem={({ item }) => { if (item.type === 'category') { const isExpanded = expandedCategoryIds.has(item.category.id); return ( <Animated.View layout={LinearTransition.easing( Easing.bezier(0.25, 0.1, 0.25, 1.0), ).duration(ANIMATION_DURATION)} > <TouchableRipple className="overflow-hidden rounded-full p-4" borderless onPress={() => toggleCategory(item.category.id)} accessibilityRole="button" accessibilityState={{ expanded: isExpanded }} accessibilityLabel={${item.category.name}, total ${Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR' }).format(item.balance)}. ${isExpanded ? 'Tap to collapse.' : 'Tap to expand.'}} > <Box className="h-full w-2" style={{ backgroundColor: item.category.color }} /> {item.category.name} {Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR', currencyDisplay: 'symbol', }).format(item.balance)} </Animated.View> ); } else { return ( <Animated.View layout={LinearTransition.easing( Easing.bezier(0.25, 0.1, 0.25, 1.0), ).duration(ANIMATION_DURATION)} entering={expand} exiting={collapse} > {Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR', currencyDisplay: 'symbol', }).format(item.record.value)} {item.record.description} </Animated.View> ); } }} recycleItems contentContainerStyle={{ paddingBottom: 60 }} /> ); };BalanceTransactionsByCategory.displayName = 'BalanceTransactionsByCategory';
Animations feel janky and I am looking to follow the Accordion official docs from React Native Reanimated: import React from 'react'; import { StyleSheet, View, Button, SafeAreaView } from 'react-native'; import Animated, { useAnimatedStyle, useDerivedValue, useSharedValue, withTiming, } from 'react-native-reanimated';
function AccordionItem({ isExpanded, children, viewKey, style, duration = 500, }) { const height = useSharedValue(0);
const derivedHeight = useDerivedValue(() => withTiming(height.value * Number(isExpanded.value), { duration, }) ); const bodyStyle = useAnimatedStyle(() => ({ height: derivedHeight.value, }));
return ( <Animated.View key={
accordionItem_${viewKey}} style={[styles.animatedView, bodyStyle, style]}> <View onLayout={(e) => { height.value = e.nativeEvent.layout.height; }} style={styles.wrapper}> {children} </Animated.View> ); }function Item() { return ; }
function Parent({ open }) { return ( ); }
export default function App() { const open = useSharedValue(false); const onPress = () => { open.value = !open.value; };
return (
<View style={styles.content}> <Parent open={open} /> </View> </SafeAreaView>); }
const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', paddingTop: 24, }, buttonContainer: { flex: 1, paddingBottom: '1rem', display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }, content: { flex: 1, justifyContent: 'center', alignItems: 'center', }, parent: { width: 200, }, wrapper: { width: '100%', position: 'absolute', display: 'flex', alignItems: 'center', }, animatedView: { width: '100%', overflow: 'hidden', }, box: { height: 120, width: 120, color: '#f8f9ff', backgroundColor: '#b58df1', borderRadius: 20, alignItems: 'center', justifyContent: 'center', }, });
The problem is records can be thousands so I am trying to use a virtualize list like LegenState List to avoid lag issues and have high FPS, that's why my data is normalized and flattened because I cannot have a ScrollView inside another ScrollView. Is it possible follow a similar approach for animation as the example code snippet?
Assistant
Okay, this is a complex problem, balancing Reanimated animations with a virtualized list like
LegendList. You're right to be concerned about performance with potentially thousands of records. Here's a breakdown of how to approach this, combining the best aspects of your current code and the Reanimated accordion example, along with explanations and potential optimizations.Understanding the Challenges
- Reanimated and Virtualization: Reanimated works best when it controls the entire rendering process. Virtualized lists (like
LegendList) manage rendering in chunks to improve performance. Directly applying Reanimated animations to items within a virtualized list can sometimes lead to conflicts or performance issues if not done carefully. - Dynamic Height: The accordion effect relies on dynamically changing the height of the content. Virtualized lists need to know the height of items to calculate which ones are visible.
- Data Normalization: Your data normalization is good for the virtualized list, but it adds complexity to the animation logic.
Revised Approach: Using
useSharedValuefor Height anduseDerivedValuefor AnimationThe key is to follow the Reanimated accordion example's pattern of using
useSharedValueto store the height anduseDerivedValueto animate it. However, we need to adapt it to work withLegendList's rendering.Here's a breakdown of the changes and a code example:
-
expandedCategoryIdsasuseSharedValue: Instead of auseStateforexpandedCategoryIds, use auseSharedValue. This allows Reanimated to track changes and trigger animations. -
Height Calculation per Category: For each category, we'll need a
useSharedValueto store its height. This height will be 0 when collapsed and the actual content height when expanded. -
useDerivedValuefor Animated Height: UseuseDerivedValueto create an animated height value based on theexpandedCategoryIdsand the category's heightuseSharedValue. -
onLayoutto Measure Content Height: Crucially, use theonLayoutprop on the category's container to measure the actual height of the content when it's first rendered (or when the content changes). Update the category's heightuseSharedValuewith this measured height. -
Apply Animated Height to
Animated.View: Wrap the category content in anAnimated.Viewand apply the animated height style. -
LegendListIntegration: TheLegendListwill render the items, and the Reanimated animations will control the height of the category content.
Code Example (Modified
BalanceTransactionsByCategoryComponent)import MaterialCommunityIcons from '@expo/vector-icons/MaterialCommunityIcons'; import { LegendList } from '@legendapp/list'; import { useContext, useMemo, useRef } from 'react'; import { View } from 'react-native'; import Animated, { useAnimatedStyle, useDerivedValue, useSharedValue, withTiming, Easing, } from 'react-native-reanimated'; import { Category, Record, RecordType } from '@/src/types/model.types'; import { MainContext } from '@components/context'; import { Box, HStack } from '@components/ui/gluestack'; import { Text, TouchableRipple } from '@components/ui/react-native-paper'; const ANIMATION_DURATION = 300; const AnimatedChevron: React.FC<{ isExpanded: useSharedValue<boolean> }> = ({ isExpanded }) => { const animatedStyle = useAnimatedStyle(() => { return { transform: [ { rotate: withTiming(isExpanded.value ? '-180deg' : '0deg', { duration: ANIMATION_DURATION, }), }, ], }; }); return ( <Animated.View style={animatedStyle}> <Text> <MaterialCommunityIcons name="menu-down" size={28} /> </Text> </Animated.View> ); }; AnimatedChevron.displayName = 'AnimatedChevron'; interface BalanceTransactionsByCategoryProps { income: number; expenses: number; recordType: RecordType; records: Record[]; } export const BalanceTransactionsByCategory: React.FC< BalanceTransactionsByCategoryProps > = ({ records, income, expenses, recordType }) => { const { categoriesMap } = useContext(MainContext); const expandedCategoryIds = useSharedValue(new Set<string>()); const categoryHeights = useRef(new Map<string, useSharedValue<number>>()); // Store heights per category const listData = useMemo(() => { const grouped = records.reduce((acc, record) => { if (record.transfer_id || record.type !== recordType) { return acc; } const categoryId = record.category_id!.toString(); const entry = acc.get(categoryId); if (entry) { entry.balance += record.value; entry.records.push(record); } else { acc.set(categoryId, { category: categoriesMap[categoryId], balance: record.value, records: [record], }); } return acc; }, new Map<string, { category: Category; balance: number; records: Record[] }>()); return Array.from(grouped.values()) .sort((a, b) => b.balance - a.balance) .flatMap((cat) => { const categoryItem = { type: 'category' as const, category: cat.category, balance: cat.balance, categoryId: cat.category.id, // Add categoryId }; const recordItems = cat.records.map((record) => ({ type: 'record' as const, record, category: cat.category, })); return [categoryItem, ...recordItems]; }); }, [records, categoriesMap, recordType]); const toggleCategory = (categoryId: string) => { expandedCategoryIds.value = new Set(expandedCategoryIds.value).add(categoryId); }; return ( <View style={{ flex: 1 }}> <LegendList data={listData} keyExtractor={(item) => item.type === 'category' ? `cat-${item.categoryId}` : `rec-${item.record.id}` } renderItem={({ item }) => { if (item.type === 'category') { const isExpanded = expandedCategoryIds.value.has(item.categoryId); // Create height shared value if it doesn't exist if (!categoryHeights.current.has(item.categoryId)) { categoryHeights.current.set(item.categoryId, useSharedValue(0)); } const categoryHeight = categoryHeights.current.get(item.categoryId)!; const animatedHeight = useDerivedValue(() => { return withTiming( isExpanded ? categoryHeight.value : 0, { duration: ANIMATION_DURATION, easing: Easing.bezier(0.25, 0.1, 0.25, 1.0) } ); }); return ( <Animated.View style={{ height: animatedHeight }} > <TouchableRipple className="overflow-hidden rounded-full p-4" borderless onPress={() => toggleCategory(item.categoryId)} accessibilityRole="button" accessibilityState={{ expanded: isExpanded }} accessibilityLabel={`${item.category.name}, total ${Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR' }).format(item.balance)}. ${isExpanded ? 'Tap to collapse.' : 'Tap to expand.'}`} > <HStack className="items-center gap-4"> <Box className="h-full w-2" style={{ backgroundColor: item.category.color }} /> <Text className="flex-1 py-2 font-bold"> {item.category.name} </Text> <Text> {Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR', currencyDisplay: 'symbol', }).format(item.balance)} </Text> <AnimatedChevron isExpanded={expandedCategoryIds} /> </HStack> </TouchableRipple> <Animated.View onLayout={(event) => { categoryHeight.value = event.nativeEvent.layout.height; }} > {/* Category Content (Records) */} {listData.filter(item => item.type === 'record' && item.category.id === item.categoryId).map((recordItem, index) => ( <HStack key={index} className="w-full py-4 pl-8" space="md"> <Text> {Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR', currencyDisplay: 'symbol', }).format(recordItem.record.value)} </Text> <Text>{recordItem.record.description}</Text> </HStack> ))} </Animated.View> </Animated.View> ); } else { return ( <Animated.View style={{ height: 50 }} // Or some default height > <HStack className="w-full py-4 pl-8" space="md"> <Text> {Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR', currencyDisplay: 'symbol', }).format(item.record.value)} </Text> <Text>{item.record.description}</Text> </HStack> </Animated.View> ); } }} recycleItems contentContainerStyle={{ paddingBottom: 60 }} /> </View> ); }; BalanceTransactionsByCategory.displayName = 'BalanceTransactionsByCategory';Key Improvements and Explanations:
expandedCategoryIdsasuseSharedValue: This is the core change. Reanimated can now react to changes in the expanded state.categoryHeightsRef: We use auseRefto store aMapofuseSharedValues, one for each category's height. This avoids recreating theuseSharedValueon every render.onLayout: TheonLayoutprop on the category content'sAnimated.Viewis essential. It measures the actual height of the content and updates thecategoryHeightuseSharedValue.useDerivedValue:animatedHeightis derived from theisExpandedstate and thecategoryHeight. This ensures smooth animation.Animated.ViewHeight: TheAnimated.Viewwrapping the category content has itsheightstyle set toanimatedHeight.- Filtering Records: The records are filtered to only show the ones that belong to the current category.
Important Considerations and Optimizations:
- Performance Testing: Thoroughly test this with a large dataset (thousands of records) to ensure it performs well. Use React Native's performance profiling tools.
recycleItems:LegendList'srecycleItemsprop is crucial for performance. Make sure it's enabled.- Memoization: Use
React.memoto memoize therenderItemfunction if it's causing unnecessary re-renders. - Content Changes: If the content within a category can change dynamically, you'll need to re-measure the height using
onLayoutwhenever the content changes. - Initial Height: Consider setting an initial height for the
categoryHeightuseSharedValueto avoid a flash of content when the component first mounts. - Complex Content: If the category content is very complex, it might still be slow to measure. You could consider simplifying the content or using a more efficient layout algorithm.
In summary, this approach combines the power of Reanimated animations with the performance benefits of a virtualized list. It requires careful attention to detail, especially the height calculation and the integration with
LegendList, but it should provide a smooth and responsive user experience even with a large number of records. Remember to test thoroughly and optimize as needed.- Reanimated and Virtualization: Reanimated works best when it controls the entire rendering process. Virtualized lists (like
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.