card-stack.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { motion } from "framer-motion";
  2. import React, { useState, useEffect } from "react";
  3. import Image from "next/image";
  4. const CARD_OFFSET = 4;
  5. const ROTATION_FACTOR = 6;
  6. interface Card {
  7. id: number;
  8. imageUrl: string;
  9. rotation: number;
  10. }
  11. interface CardStackProps {
  12. photos: string[];
  13. }
  14. const CardStack: React.FC<CardStackProps> = ({ photos }) => {
  15. const [cards, setCards] = useState<Card[]>([]);
  16. useEffect(() => {
  17. if (photos.length > 0) {
  18. const initialCards = photos.map((imageUrl, index) => ({
  19. id: index,
  20. imageUrl: imageUrl,
  21. rotation: (index % 2 === 0 ? 1 : -1) * ROTATION_FACTOR * Math.random(),
  22. }));
  23. setCards(initialCards);
  24. }
  25. }, [photos]);
  26. const moveToEnd = (from: number) => {
  27. setCards((prevCards) => {
  28. const newCards = [...prevCards];
  29. const item = newCards.splice(from, 1)[0];
  30. newCards.push(item);
  31. return newCards;
  32. });
  33. };
  34. return (
  35. <ul className="h-full w-full flex justify-center items-center mt-4">
  36. {cards.map((card, index) => (
  37. <motion.li
  38. key={card.id}
  39. animate={{
  40. y: index * -CARD_OFFSET,
  41. rotate: card.rotation,
  42. }}
  43. className="absolute origin-center list-none rounded-lg cursor-grab"
  44. drag="y"
  45. dragConstraints={{
  46. top: 0,
  47. bottom: 0,
  48. }}
  49. initial={{ rotate: card.rotation }}
  50. style={{
  51. zIndex: cards.length - index,
  52. }}
  53. transition={{ type: "spring", stiffness: 50 }}
  54. onDragEnd={() => moveToEnd(index)}
  55. onMouseDown={(e) => e.stopPropagation()}
  56. >
  57. <Image
  58. alt="Card image"
  59. className="object-cover w-[80%] mx-auto md:w-full rounded-2xl aspect-video"
  60. height={200}
  61. quality={80}
  62. src={card.imageUrl}
  63. width={355}
  64. />
  65. </motion.li>
  66. ))}
  67. </ul>
  68. );
  69. };
  70. export default CardStack;