card-stack.tsx 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. "use client";
  2. import { motion } from "framer-motion";
  3. import React, { useState, useMemo } from "react";
  4. import { BlurImage } from "./blur-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. // Generate stable rotations based on index (deterministic)
  16. function getRotation(index: number): number {
  17. // Use a seeded pseudo-random based on index for consistency
  18. const seed = (index * 9301 + 49297) % 233280;
  19. const random = seed / 233280;
  20. return (index % 2 === 0 ? 1 : -1) * ROTATION_FACTOR * random;
  21. }
  22. const CardStack: React.FC<CardStackProps> = ({ photos }) => {
  23. const initialCards = useMemo(
  24. () =>
  25. photos.map((imageUrl, index) => ({
  26. id: index,
  27. imageUrl,
  28. rotation: getRotation(index),
  29. })),
  30. [photos],
  31. );
  32. const [cards, setCards] = useState<Card[]>(initialCards);
  33. const moveToEnd = (from: number) => {
  34. setCards((prevCards) => {
  35. const newCards = [...prevCards];
  36. const item = newCards.splice(from, 1)[0];
  37. newCards.push(item);
  38. return newCards;
  39. });
  40. };
  41. return (
  42. <ul className="h-full w-full flex justify-center items-center mt-4">
  43. {cards.map((card, index) => (
  44. <motion.li
  45. key={card.id}
  46. animate={{
  47. y: index * -CARD_OFFSET,
  48. rotate: card.rotation,
  49. }}
  50. className="absolute origin-center list-none rounded-lg cursor-grab"
  51. drag="y"
  52. dragConstraints={{ top: 0, bottom: 0 }}
  53. initial={{ rotate: card.rotation }}
  54. style={{ zIndex: cards.length - index }}
  55. transition={{ type: "spring" as const, stiffness: 50 }}
  56. onDragEnd={() => moveToEnd(index)}
  57. onMouseDown={(e) => e.stopPropagation()}
  58. >
  59. <BlurImage
  60. alt="Card image"
  61. className="object-cover w-[80%] mx-auto md:w-full rounded-2xl aspect-video"
  62. containerClassName="rounded-2xl"
  63. height={200}
  64. loading={index === cards.length - 1 ? "eager" : "lazy"}
  65. quality={60}
  66. sizes="(max-width: 768px) 200px, 355px"
  67. src={card.imageUrl}
  68. width={355}
  69. />
  70. </motion.li>
  71. ))}
  72. </ul>
  73. );
  74. };
  75. export default CardStack;