import React, { useState, useCallback, useMemo, useEffect, useRef, } from "react";…
- User
import React, { useState, useCallback, useMemo, useEffect, useRef, } from "react"; import { motion, AnimatePresence, useMotionValue, useTransform, } from "framer-motion"; import Image from "next/image";
import ExploreImage from "@/../public/maintenance/projects/personalized-fashion-platfrom/images/Explore.png"; import FabricsCollectionImage from "@/../public/maintenance/projects/personalized-fashion-platfrom/images/Fabrics Collection.png"; import ProductImage from "@/../public/maintenance/projects/personalized-fashion-platfrom/images/Product.png"; import SearchImage from "@/../public/maintenance/projects/personalized-fashion-platfrom/images/Search.png"; import SignInEmailImage from "@/../public/maintenance/projects/personalized-fashion-platfrom/images/Sign In - Email.png"; import SignInPasswordImage from "@/../public/maintenance/projects/personalized-fashion-platfrom/images/Sign In - Password.png"; import SignInImage from "@/../public/maintenance/projects/personalized-fashion-platfrom/images/Sign In.png"; import SizeProfile1Image from "@/../public/maintenance/projects/personalized-fashion-platfrom/images/Size Profile-1.png"; import SizeProfile2Image from "@/../public/maintenance/projects/personalized-fashion-platfrom/images/Size Profile-2.png"; import SizeProfileImage from "@/../public/maintenance/projects/personalized-fashion-platfrom/images/Size Profile.png"; import SizingAdjustmentsImage from "@/../public/maintenance/projects/personalized-fashion-platfrom/images/Sizing Adjustments.png"; import SplashScreenImage from "@/../public/maintenance/projects/personalized-fashion-platfrom/images/Splash Screen.png";
enum ScreenSize { MOBILE = "mobile", TABLET = "tablet", WEB = "web", }
interface ProjectImage { id: string; title: string; subtitle: string; screenSize: ScreenSize; href: any; }
interface Project { id: number; name: string; description: string; images: ProjectImage[]; }
interface ProjectGroup { id: number; name: string; projects: Project[]; }
// Image dimensions in pixels const IMAGE_WIDTH = 383; const IMAGE_HEIGHT = 852;
const importAll = (r: any) => { let images: any = {}; r.keys().forEach((item: any) => { images[item.replace("./", "")] = r(item); }); return images; };
const projectGroupsData: ProjectGroup[] = [ { id: 1, name: "Personalized Fashion Platform", projects: [ { id: 201, name: "Fashion App Screens", description: "Various screens from our personalized fashion platform", images: [ { id: "201-explore", title: "Explore Screen", subtitle: "Discover new styles", screenSize: ScreenSize.MOBILE, href: ExploreImage, }, { id: "201-fabrics", title: "Fabrics Collection", subtitle: "Browse fabric options", screenSize: ScreenSize.MOBILE, href: FabricsCollectionImage, }, { id: "201-product", title: "Product Screen", subtitle: "View product details", screenSize: ScreenSize.MOBILE, href: ProductImage, }, { id: "201-search", title: "Search Screen", subtitle: "Find your perfect style", screenSize: ScreenSize.MOBILE, href: SearchImage, }, { id: "201-signin-email", title: "Sign In - Email", subtitle: "Enter your email", screenSize: ScreenSize.MOBILE, href: SignInEmailImage, }, { id: "201-signin-password", title: "Sign In - Password", subtitle: "Enter your password", screenSize: ScreenSize.MOBILE, href: SignInPasswordImage, }, { id: "201-signin", title: "Sign In", subtitle: "Access your account", screenSize: ScreenSize.MOBILE, href: SignInImage, }, { id: "201-size-profile-1", title: "Size Profile - Step 1", subtitle: "Enter your measurements", screenSize: ScreenSize.MOBILE, href: SizeProfile1Image, }, { id: "201-size-profile-2", title: "Size Profile - Step 2", subtitle: "Refine your fit", screenSize: ScreenSize.MOBILE, href: SizeProfile2Image, }, { id: "201-size-profile", title: "Size Profile", subtitle: "View your size profile", screenSize: ScreenSize.MOBILE, href: SizeProfileImage, }, { id: "201-sizing-adjustments", title: "Sizing Adjustments", subtitle: "Fine-tune your fit", screenSize: ScreenSize.MOBILE, href: SizingAdjustmentsImage, }, { id: "201-splash", title: "Splash Screen", subtitle: "Welcome to the app", screenSize: ScreenSize.MOBILE, href: SplashScreenImage, }, ], }, ], }, ];
const GroupedWheelControlledCarousel = () => { const itemGroups = useMemo( () => projectGroupsData.map((group) => ({ id: group.id, name: group.name, items: group.projects.flatMap((project) => project.images.map((image) => ({ id: image.id, item: image.href, title: image.title, subtitle: image.subtitle, projectName: project.name, projectDescription: project.description, screenSize: image.screenSize, })), ), })), [], );
const flattenedItems = useMemo( () => itemGroups.flatMap((group) => group.items.map((item, idx) => ({ ...item, groupId: group.id, groupName: group.name, id:
${group.id}-${idx}, })), ), [itemGroups], );const totalItems = flattenedItems.length; const [visibleItemCount, setVisibleItemCount] = useState(7); const [containerWidth, setContainerWidth] = useState(600); const [containerHeight, setContainerHeight] = useState(200);
const [offset, setOffset] = useState(0); const dragX = useMotionValue(0); const containerRef = useRef(null);
useEffect(() => { const handleWheel = (event: WheelEvent) => { event.preventDefault(); const delta = event.deltaX * 0.005; // Reduced multiplier for smoother scrolling setOffset((prevOffset) => { const newOffset = prevOffset + delta; return newOffset - Math.floor(newOffset / totalItems) * totalItems; }); };
const container = containerRef.current; if (container) { container.addEventListener("wheel", handleWheel, { passive: false }); } return () => { if (container) { container.removeEventListener("wheel", handleWheel); } };}, [totalItems]);
const handleDrag = useCallback( (event: any, info: any) => { const dragDelta = info.delta.x * 0.005; // Adjust this multiplier as needed setOffset((prevOffset) => { const newOffset = prevOffset - dragDelta; return newOffset - Math.floor(newOffset / totalItems) * totalItems; }); }, [totalItems], );
const visibleItems = useMemo(() => { const items = []; const halfVisible = Math.floor(visibleItemCount / 2);
for (let i = -halfVisible; i <= halfVisible; i++) { const itemIndex = Math.floor(offset + i); const wrappedIndex = ((itemIndex % totalItems) + totalItems) % totalItems; const item = flattenedItems[wrappedIndex]; const position = (i - (offset % 1)) / halfVisible; // Calculate opacity based on position const opacity = Math.cos((position * Math.PI) / 2); // Only include items with opacity > 0 if (opacity > 0) { items.push({ ...item, position, opacity, }); } } return items;}, [offset, flattenedItems, totalItems, visibleItemCount]);
const activeGroups = useMemo(() => { const groups = new Set(visibleItems.map((item) => item.groupId)); return groups; }, [visibleItems]);
const pathD = useMemo(() => { const midY = containerHeight / 2; const controlY = containerHeight / 4; const rx = containerWidth / 2 + 360; const ry = containerHeight / 2 - 40; const centerX = containerWidth / 2; const centerY = containerHeight / 2; const startAngle = 150 * (Math.PI / 180); const endAngle = 30 * (Math.PI / 180);
const startX = centerX + rx * Math.cos(startAngle); const startY = centerY + ry * Math.sin(startAngle); const endX = centerX + rx * Math.cos(endAngle); const endY = centerY + ry * Math.sin(endAngle); return `M${startX},${startY} A${rx},${ry} 0 0 0 ${endX},${endY}`;}, [containerWidth, containerHeight]);
return ( <motion.div ref={containerRef} className="relative mb-4 flex items-center justify-center overflow-visible rounded-lg bg-gray-100" style={{ width:
${100}%, height:${(containerWidth / 5) * (IMAGE_HEIGHT / IMAGE_WIDTH)}px, }} drag="x" dragConstraints={{ left: 0, right: 0 }} dragElastic={0.05} onDrag={handleDrag} > <svg width={"100%"} height={containerHeight} className="absolute left-0 top-0" > <div style={{ width:${containerWidth}px, height:${(containerWidth / 5) * (IMAGE_HEIGHT / IMAGE_WIDTH)}px, }} > {visibleItems.map((itemObj) => { const normalizedPosition = (itemObj.position + 1) / 2; // Convert position to range 0-1 const distanceFromCenter = Math.abs(normalizedPosition - 0.5); const opacity = Math.max(0, 1 - distanceFromCenter * 0.5); // Faster fade-out const scale = 0.8 + (1 - distanceFromCenter) * 0.5; // Scale down towards edgesreturn ( <motion.div key={itemObj.id} className="absolute -translate-x-1/2 -translate-y-1/2 transform opacity-0" style={{ offsetPath: `path("${pathD}")`, offsetDistance: `${normalizedPosition * 100}%`, opacity: opacity, zIndex: Math.round((1 - distanceFromCenter) * 100), pointerEvents: opacity > 0.1 ? "auto" : "none", // Disable interactions for nearly invisible items }} initial={{ opacity: 0, scale: 0.8 }} animate={{ opacity: opacity, scale: scale }} exit={{ opacity: 0, scale: 0.8 }} transition={{ duration: 0.1, opacity: { duration: 0.07, }, }} > <Image src={itemObj.item} alt={`${itemObj.projectName} - ${itemObj.title}`} width={containerWidth / 5} height={(containerWidth / 5) * (IMAGE_HEIGHT / IMAGE_WIDTH)} className="rounded-lg object-cover" /> </motion.div> ); })} </AnimatePresence> </div> </motion.div> <div className="flex justify-center space-x-2"> {itemGroups.map((group) => ( <div key={group.id} className={`h-3 w-3 rounded-full ${ activeGroups.has(group.id) ? "bg-blue-500" : "bg-gray-300" }`} title={group.name} /> ))} </div> <div className="mt-2 text-center"> Active Groups:{" "} {Array.from(activeGroups) .map((groupId) => { const group = itemGroups.find((g) => g.id === groupId); return group ? group.name : ""; }) .join(", ")} </div> </div>); };
export default GroupedWheelControlledCarousel;
Use framer motion.
- Assistant
It looks like you're working on a wheel-controlled carousel using React and Framer Motion, and you want to ensure that you're effectively leveraging Framer Motion's capabilities in your implementation. Let's walk through your code and see how we can enhance it using Framer Motion.
Understanding Your Current Implementation
Your component
GroupedWheelControlledCarouselis designed to:- Display a set of images grouped by projects.
- Allow users to scroll through the images using the mouse wheel.
- Animate the items along a path, adjusting their position, scale, and opacity based on their relative position in the carousel.
You've imported necessary React hooks and Framer Motion components, and you're using
motion.divandAnimatePresencefor animations.Key Areas to Enhance with Framer Motion
-
Motion Values and Animations: You can make better use of Framer Motion's
useMotionValueanduseTransformhooks to create smoother animations and reactive UI elements. -
Drag and Scroll Handling: Framer Motion provides built-in drag controls and supports gesture animations, which can simplify your drag and wheel interactions.
-
Optimizing Performance: By using Framer Motion's features effectively, you can ensure that your animations are smooth and performant.
Enhancing Your Carousel with Framer Motion
Let's refactor your carousel to make better use of Framer Motion.
1. Managing Scroll Offset with
useMotionValueInstead of using React's
useStateforoffset, we can useuseMotionValue:const offset = useMotionValue(0);This allows us to smoothly animate values and use Framer Motion's reactivity.
2. Handling Wheel Events
We can use Framer Motion's
useAnimationcontrols to animate theoffsetwhen the wheel event occurs:const controls = useAnimation(); useEffect(() => { const handleWheel = (event) => { event.preventDefault(); const delta = -event.deltaY * 0.005; controls.start({ x: offset.get() + delta, transition: { type: 'spring', stiffness: 300, damping: 30 }, }); offset.set(offset.get() + delta); }; const container = containerRef.current; if (container) { container.addEventListener('wheel', handleWheel, { passive: false }); } return () => { if (container) { container.removeEventListener('wheel', handleWheel); } }; }, [controls, offset]);3. Animating Item Positions with
useTransformWe can use
useTransformto map theoffsetto each item's position, scale, and opacity:const itemPosition = useTransform(offset, (value) => { // Calculate the position for each item based on the offset value // Return the transformed value }); const itemScale = useTransform(offset, (value) => { // Calculate scale based on the position }); const itemOpacity = useTransform(offset, (value) => { // Calculate opacity based on the position });Then apply these motion values directly to the item components.
4. Simplifying Dragging with Framer Motion
Since you're using
motion.divfor the container, you can leverage Framer Motion's drag capabilities:<motion.div ref={containerRef} className="carousel-container" drag="x" dragConstraints={{ left: -maxOffset, right: 0 }} dragElastic={0.2} onDrag={(event, info) => { offset.set(offset.get() + info.delta.x * 0.01); }} > {/* Carousel items */} </motion.div>5. Updating the Item Rendering
When rendering the items, use the motion values for style properties:
{visibleItems.map((item, index) => ( <motion.div key={item.id} className="carousel-item" style={{ x: itemPosition, scale: itemScale, opacity: itemOpacity, }} > <Image src={item.item} alt={`${item.projectName} - ${item.title}`} layout="responsive" width={IMAGE_WIDTH} height={IMAGE_HEIGHT} /> </motion.div> ))}Complete Refactored Example
Here's how your
GroupedWheelControlledCarouselcomponent might look after integrating the above suggestions. Note that due to the complexity and length, this is a simplified version focusing on key aspects.import React, { useMemo, useEffect, useRef } from "react"; import { motion, useMotionValue, useTransform } from "framer-motion"; import Image from "next/image"; // ... (Your imports and data definitions remain the same) const GroupedWheelControlledCarousel = () => { const itemGroups = useMemo( () => projectGroupsData.map((group) => ({ id: group.id, name: group.name, items: group.projects.flatMap((project) => project.images.map((image) => ({ id: image.id, item: image.href, title: image.title, subtitle: image.subtitle, projectName: project.name, projectDescription: project.description, screenSize: image.screenSize, })) ), })), [] ); const flattenedItems = useMemo( () => itemGroups.flatMap((group) => group.items.map((item, idx) => ({ ...item, groupId: group.id, groupName: group.name, id: `${group.id}-${idx}`, })) ), [itemGroups] ); const totalItems = flattenedItems.length; const visibleItemCount = 7; const offset = useMotionValue(0); // Use MotionValue for smooth animations const containerRef = useRef(null); useEffect(() => { const handleWheel = (event) => { event.preventDefault(); const delta = -event.deltaY * 0.002; // Adjust sensitivity offset.set(offset.get() + delta); }; const container = containerRef.current; if (container) { container.addEventListener("wheel", handleWheel, { passive: false }); } return () => { if (container) { container.removeEventListener("wheel", handleWheel); } }; }, [offset]); const visibleItems = useMemo(() => { const items = []; const halfVisible = Math.floor(visibleItemCount / 2); for (let i = -halfVisible; i <= halfVisible; i++) { const itemIndex = Math.floor(offset.get() + i); const wrappedIndex = ((itemIndex % totalItems) + totalItems) % totalItems; const item = flattenedItems[wrappedIndex]; const position = i - (offset.get() % 1); items.push({ ...item, position, }); } return items; }, [offset, flattenedItems, totalItems, visibleItemCount]); return ( <div className="carousel-wrapper"> <motion.div ref={containerRef} className="carousel-container" drag="x" dragConstraints={{ left: 0, right: 0 }} dragElastic={0.2} onDrag={(event, info) => { offset.set(offset.get() + info.delta.x * 0.005); }} > {visibleItems.map((item) => { const scale = useTransform(offset, (value) => { const distance = Math.abs(item.position); return Math.max(0.8, 1 - distance * 0.1); }); const opacity = useTransform(offset, (value) => { const distance = Math.abs(item.position); return Math.max(0, 1 - distance * 0.3); }); const x = useTransform(offset, (value) => { return item.position * 200; // Adjust the multiplier for spacing }); return ( <motion.div key={item.id} className="carousel-item" style={{ x, scale, opacity, position: "absolute", left: "50%", top: "50%", translateX: "-50%", translateY: "-50%", }} > <Image src={item.item} alt={`${item.projectName} - ${item.title}`} width={IMAGE_WIDTH} height={IMAGE_HEIGHT} className="rounded-lg object-cover" /> </motion.div> ); })} </motion.div> {/* Dots or other indicators */} </div> ); }; export default GroupedWheelControlledCarousel;Notes:
-
Motion Values (
useMotionValueanduseTransform): We've useduseMotionValuefor theoffsetto create a smooth, continuous animation that reacts to user input. -
Wheel and Drag Interaction: Both wheel and drag events update the
offsetvalue, which in turn updates positions, scales, and opacities of the items. -
Item Positioning: By calculating each item's position relative to the
offset, we can create a smooth carousel effect. -
Framer Motion Animations: Applying transforms directly through
styleprop using motion values ensures smooth animations without the need for explicitanimateortransitionprops.
Additional Tips
-
Avoid Overlapping Identifiers: Make sure your
keyprops are unique to prevent React from reusing components incorrectly. -
Responsive Design: Adjust the calculations based on the container's width and height to ensure the carousel is responsive.
-
Optimizing Performance: Limit the number of items rendered to only what's visible to improve performance, which you're already doing with
visibleItems. -
Accessibility: Consider adding ARIA roles and keyboard interactions for better accessibility.
Conclusion
By leveraging Framer Motion's powerful hooks and features, we can simplify your carousel implementation and create smooth, interactive animations. The key is to use motion values for any state that affects animation and to apply transformations directly through style attributes using these motion values.
Feel free to adjust the values and functions to better fit your specific design and performance needs. If you have any questions or need further assistance, don't hesitate to ask!