import React, { useState, useCallback, useMemo, useEffect } from "react"; import {…
- User
import React, { useState, useCallback, useMemo, useEffect } from "react"; import { motion, AnimatePresence } from "framer-motion"; import Image from "next/image";
enum ScreenSize { MOBILE = "mobile", TABLET = "tablet", WEB = "web", }
interface ProjectImage { id: string; title: string; subtitle: string; screenSize: ScreenSize; href: string; }
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 projectGroupsData: ProjectGroup[] = [ { id: 1, name: "Nature", projects: [ { id: 201, name: "Mountain Vista", description: "Breathtaking view of mountain ranges", images: [ { id: "201-web", title: "Mountain Peak", subtitle: "Snowy caps", screenSize: ScreenSize.WEB, href:
https://picsum.photos/id/201/${IMAGE_WIDTH}/${IMAGE_HEIGHT}, }, { id: "201-mobile", title: "Mountain Mobile", subtitle: "Compact view", screenSize: ScreenSize.MOBILE, href:https://picsum.photos/id/202/${IMAGE_WIDTH}/${IMAGE_HEIGHT}, }, ], }, { id: 202, name: "Serene Lake", description: "Calm waters reflecting surrounding nature", images: [ { id: "202-web", title: "Lake View", subtitle: "Mirror-like surface", screenSize: ScreenSize.WEB, href:https://picsum.photos/id/203/${IMAGE_WIDTH}/${IMAGE_HEIGHT}, }, { id: "202-mobile", title: "Lake Mobile", subtitle: "Vertical panorama", screenSize: ScreenSize.MOBILE, href:https://picsum.photos/id/204/${IMAGE_WIDTH}/${IMAGE_HEIGHT}, }, ], }, ], }, { id: 2, name: "Architecture", projects: [ { id: 301, name: "Modern Skyscraper", description: "Sleek design of urban architecture", images: [ { id: "301-web", title: "Skyscraper View", subtitle: "City skyline", screenSize: ScreenSize.WEB, href:https://picsum.photos/id/301/${IMAGE_WIDTH}/${IMAGE_HEIGHT}, }, { id: "301-mobile", title: "Skyscraper Mobile", subtitle: "Vertical view", screenSize: ScreenSize.MOBILE, href:https://picsum.photos/id/302/${IMAGE_WIDTH}/${IMAGE_HEIGHT}, }, ], }, { id: 302, name: "Historic Bridge", description: "Iconic bridge with classic architecture", images: [ { id: "302-web", title: "Bridge Span", subtitle: "Engineering marvel", screenSize: ScreenSize.WEB, href:https://picsum.photos/id/303/${IMAGE_WIDTH}/${IMAGE_HEIGHT}, }, { id: "302-mobile", title: "Bridge Mobile", subtitle: "Vertical perspective", screenSize: ScreenSize.MOBILE, href:https://picsum.photos/id/304/${IMAGE_WIDTH}/${IMAGE_HEIGHT}, }, ], }, ], }, ];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);
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; }); };
window.addEventListener("wheel", handleWheel, { passive: false }); return () => { window.removeEventListener("wheel", handleWheel); };}, [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 ( <div 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, }} > <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.4; // 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> </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; simplify implementation using framer motion utilities like useTransform. but still should work same.
- Assistant
Certainly! You can simplify your carousel implementation by leveraging Framer Motion's
useMotionValueanduseTransformhooks. These hooks allow you to create reactive animations based on motion values without manually calculating positions and styles.Here's how you can refactor your code:
-
Use
useMotionValuefor the offset: This replaces the state variableoffsetwith a motion value, allowing for smoother animations and direct integration with Framer Motion. -
Use
useTransformto derive item properties: By transforming theoffsetmotion value, you can calculate each item's position, opacity, and scale more elegantly. -
Utilize Framer Motion's SVG path utilities: Instead of manually calculating the offset along a path, you can use Framer Motion's
motion.pathand animate items along an SVG path.
Below is the refactored code with these changes implemented:
import React, { useMemo, useEffect } from "react"; import { motion, useMotionValue, useTransform } from "framer-motion"; import Image from "next/image"; enum ScreenSize { MOBILE = "mobile", TABLET = "tablet", WEB = "web", } interface ProjectImage { id: string; title: string; subtitle: string; screenSize: ScreenSize; href: string; } 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 projectGroupsData: ProjectGroup[] = [ // ... (same as your initial data) ]; 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; // Replace state with motion values const offset = useMotionValue(0); useEffect(() => { const handleWheel = (event: WheelEvent) => { event.preventDefault(); offset.set(offset.get() + event.deltaY * 0.001); }; window.addEventListener("wheel", handleWheel, { passive: false }); return () => { window.removeEventListener("wheel", handleWheel); }; }, [offset]); const visibleItemCount = 7; const halfVisible = Math.floor(visibleItemCount / 2); // Prepare transforms const indices = useMemo( () => Array.from({ length: totalItems }, (_, i) => i), [totalItems] ); const items = indices.map((index) => { const item = flattenedItems[index]; // Calculate position relative to the offset const position = useTransform(offset, (value) => { const pos = index - (value % totalItems); return ((pos + totalItems + halfVisible) % totalItems) - halfVisible; }); // Map position to scale and opacity const scale = useTransform(position, [-halfVisible, 0, halfVisible], [0.8, 1, 0.8]); const opacity = useTransform(position, [-halfVisible, 0, halfVisible], [0, 1, 0]); // Calculate offset along path const offsetDistance = useTransform(position, [-halfVisible, halfVisible], [0, 1]); return { ...item, position, scale, opacity, offsetDistance, }; }); const activeGroups = useMemo(() => { const visibleIndices = indices.filter((_, i) => { const pos = items[i].position.get(); return pos >= -halfVisible && pos <= halfVisible; }); return new Set(visibleIndices.map((i) => flattenedItems[i].groupId)); }, [items, indices, flattenedItems, halfVisible]); // SVG Path const pathD = ` M 100,200 C 300,-50 500,450 700,200 `; return ( <div className="mx-auto h-full w-full"> <div className="relative mb-4 flex items-center justify-center overflow-visible rounded-lg bg-gray-100"> <svg width={"100%"} height={"400px"} className="absolute left-0 top-0"> <path d={pathD} fill="none" stroke="lightgray" /> </svg> <div className="relative"> {items.map((itemObj) => ( <motion.div key={itemObj.id} className="absolute -translate-x-1/2 -translate-y-1/2" style={{ offsetPath: `path("${pathD}")`, offsetDistance: itemObj.offsetDistance, scale: itemObj.scale, opacity: itemObj.opacity, zIndex: itemObj.opacity, }} > <Image src={itemObj.item} alt={`${itemObj.projectName} - ${itemObj.title}`} width={150} height={300} className="rounded-lg object-cover" /> </motion.div> ))} </div> </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;Explanation of Changes
-
Motion Values: Replaced the state variable
offsetwith a motion value usinguseMotionValue(0). Motion values are reactive and integrate seamlessly with Framer Motion's animation utilities. -
useTransform: Used
useTransformto derive item properties (position,scale,opacity,offsetDistance) based on theoffsetmotion value. This replaces manual calculations and makes the code more concise. -
SVG Path Animation: Simplified the SVG path and used
offsetPathandoffsetDistancein themotion.divstyles to animate items along the path. -
Removed Manual Calculations: The manual calculations for positions, opacities, scales, and offsets are now handled by
useTransform, reducing the complexity of the code.
Benefits of This Approach
-
Simpler Code: By leveraging
useMotionValueanduseTransform, the code becomes more readable and maintainable. -
Smooth Animations: Motion values provide inherent animation capabilities, resulting in smoother transitions and interactions.
-
Reactivity: Changes to motion values automatically update the transforms, keeping the UI in sync with user interactions.
Notes
-
SVG Path Adjustments: You may need to adjust the SVG path (
pathD) to fit your design requirements. The provided path is a placeholder for demonstration. -
Styling and Dimensions: Adjust the
width,height, and other styling properties as needed to fit your application's layout. -
Wheel Event Sensitivity: Adjust the multiplier in
event.deltaY * 0.001to control the sensitivity of the wheel scrolling.
Final Thoughts
By utilizing Framer Motion's utilities, you've reduced the complexity of your carousel implementation while maintaining its functionality. The use of
useTransformmakes it easier to map input values to animated properties, providing a more declarative and intuitive approach to animations.Let me know if you need further assistance or have any questions!
-