Look at my code: import MaterialCommunityIcons from…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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?
Okay, I see what you're trying to achieve. You want the smooth, controlled animation of the Reanimated Accordion example, but within the constraints of a virtualized list (LegendList) where items are rendered on demand.
The core difference between your current approach for records and the Reanimated Accordion example is how visibility is handled:
entering/exiting): This is perfect for items that are added to or removed from the LegendList's data. When a category expands, you want its records to appear in the list. When it collapses, you want them to disappear. Your expand/collapse worklets correctly define how they should animate in/out.useSharedValue, onLayout, useDerivedValue): This example is designed for a scenario where an item remains in the DOM (or virtual DOM), but its height is animated. It measures its own content's height and then animates that measured height to 0 or its full value. This is great if you're not using a virtualized list, or if you had a fixed number of items that always stayed mounted.The Problem with Your Current listData for Toggling:
Your listData generation currently flattens all records for all categories from the start:
.flatMap((cat) => {
const categoryItem = { ... };
const recordItems = cat.records.map((record) => ({ ... }));
return [categoryItem, ...recordItems]; // Records are always included here
});
This means record items are always present in listData. When you toggle a category, you're relying on expandedCategoryIds to know if it's expanded, but the record items themselves are still technically in the list's data, which might prevent the entering/exiting animations from behaving as expected for a simple hide/show within an already rendered parent.
The Solution: Dynamically Filter listData and Use entering/exiting Correctly
The key to making this work smoothly with LegendList and achieve the accordion effect is to only include the record items in listData when their parent category is actually expanded. This way, when a category is expanded, its records will be "added" to the 's data, triggering your animation. When collapsed, they'll be "removed," triggering .
LegendListenteringexitingHere's how to modify your listData generation:
Add expandedCategoryIds to useMemo dependencies:
Your listData needs to recompute whenever expandedCategoryIds changes.
Conditionally add recordItems:
Inside the flatMap, check if the current category's ID is in expandedCategoryIds. If it is, include its records; otherwise, only include the category header.
Modified 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;
// Your existing expand/collapse worklets are good for entering/exiting items
const expand = (values: EntryAnimationsValues): LayoutAnimation => {
'worklet';
return {
initialValues: {
height: 0,
opacity: 0,
},
animations: {
height: withTiming(values.targetHeight, { duration: ANIMATION_DURATION, easing: Easing.bezier(0.25, 0.1, 0.25, 1.0) }), // Added easing for consistency
opacity: withTiming(1, { duration: ANIMATION_DURATION, easing: Easing.bezier(0.25, 0.1, 0.25, 1.0) }), // Added easing for consistency
},
};
};
const collapse = (values: ExitAnimationsValues): LayoutAnimation => {
'worklet';
return {
initialValues: {
height: values.currentHeight,
opacity: 1,
},
animations: {
height: withTiming(0, { duration: ANIMATION_DURATION, easing: Easing.bezier(0.25, 0.1, 0.25, 1.0) }), // Added easing for consistency
opacity: withTiming(0, { duration: ANIMATION_DURATION, easing: Easing.bezier(0.25, 0.1, 0.25, 1.0) }), // Added easing for consistency
},
};
};
const AnimatedChevron: React.FC<{ isExpanded: boolean }> = ({ isExpanded }) => {
const animatedStyle = useAnimatedStyle(() => {
return {
transform: [
{
rotate: withTiming(isExpanded ? '180deg' : '0deg', { // Changed to 180deg for standard chevron collapse
duration: ANIMATION_DURATION,
easing: Easing.bezier(0.25, 0.1, 0.25, 1.0), // Added easing
}),
},
],
};
});
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, setExpandedCategoryIds] = useState(
new Set<string>(),
);
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,
};
// *** THIS IS THE CRUCIAL CHANGE ***
// Only include records if the category is expanded
if (expandedCategoryIds.has(cat.category.id)) {
const recordItems = cat.records.map((record) => ({
type: 'record' as const,
record,
category: cat.category,
}));
return [categoryItem, ...recordItems];
} else {
// If not expanded, only return the category header
return [categoryItem];
}
});
// *** Added expandedCategoryIds to the dependency array ***
}, [records, categoriesMap, recordType, expandedCategoryIds]);
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 (
// The LinearTransition here animates the category header's position if its children change layout,
// which is fine. The records themselves will use entering/exiting.
<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.'}`}
>
<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={isExpanded} />
</HStack>
</TouchableRipple>
</Animated.View>
);
} else { // item.type === 'record'
// *** Use entering/exiting for record items ***
// The `Animated.View` itself will have its height animated by the worklets.
// `overflow: 'hidden'` is important to clip the content during height animation.
return (
<Animated.View
// Removed layout={LinearTransition...} as entering/exiting handles the animation
entering={expand} // This will run when a record item is added to listData
exiting={collapse} // This will run when a record item is removed from listData
style={{ overflow: 'hidden' }} // Ensure content is clipped during animation
>
<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';
Explanation of Changes:
useMemo Dependency: expandedCategoryIds is now a dependency for listData. Whenever you toggleCategory, listData will be recomputed.recordItems: The .flatMap now checks expandedCategoryIds.has(cat.category.id).
true, it returns [categoryItem, ...recordItems]. This tells LegendList to render the category header and all its associated records. When these records are added to the list's data, the entering={expand} prop will trigger their animation from 0 height/opacity to their natural height/opacity.false, it returns only [categoryItem]. This tells LegendList to remove any records previously associated with this category. The exiting={collapse} prop will then trigger their animation from their current height/opacity down to 0.Animated.View for Records: The Animated.View wrapping the HStack for each record item now correctly uses entering={expand} and exiting={collapse}. The layout={LinearTransition...} has been removed from the record items because entering/exiting are the specific props for handling the animation of items being added/removed from the list. LinearTransition is more for animating items that stay in the list but change their position/size due to other list changes.overflow: 'hidden': Added this style to the record Animated.View. This is crucial for the height animation to work correctly, as it clips the content outside the animated bounds.LinearTransition to your expand/collapse worklets and the chevron animation for consistency. I also adjusted the chevron rotation to 180deg for a more typical "collapsed" state icon.This approach leverages Reanimated's entering/exiting animations, which are designed precisely for animating items appearing and disappearing in virtualized lists like LegendList, effectively giving you the smooth accordion behavior you're looking for without needing the onLayout measurement logic that's more suited to non-virtualized lists.