card-stack.tsx 2.0 KB

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