photo-deck.tsx 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. "use client";
  2. import Image from "next/image";
  3. import {
  4. useLayoutEffect,
  5. useRef,
  6. useState,
  7. type PointerEvent as ReactPointerEvent,
  8. } from "react";
  9. import { useT } from "@/components/locale-provider";
  10. import { springs } from "@/lib/motion";
  11. import { cn, prefersReducedMotion } from "@/lib/utils";
  12. const DEPTH = 4;
  13. const tilt = (n: number) => (((n * 9301 + 49297) % 233280) / 233280 - 0.5) * 9;
  14. type Gesture = {
  15. x: number;
  16. y: number;
  17. dx: number;
  18. dy: number;
  19. t: number;
  20. v: number;
  21. };
  22. /**
  23. * A deck of photos: hover to fan it, fling the top photo away (or tap it),
  24. * or step through with the buttons. Gestures move the whole card.
  25. */
  26. export function PhotoDeck({ photos }: { photos: string[] }) {
  27. const { photos: t } = useT();
  28. const [order, setOrder] = useState(() => photos.map((_, i) => i));
  29. const [seen, setSeen] = useState(0);
  30. const [fanned, setFanned] = useState(false);
  31. const topRef = useRef<HTMLDivElement>(null);
  32. const gesture = useRef<Gesture | null>(null);
  33. const busy = useRef(false);
  34. /** Set when the next render should slide a photo back onto the top. */
  35. const returning = useRef(false);
  36. // A photo stepped back onto the deck glides in from the left.
  37. useLayoutEffect(() => {
  38. const el = topRef.current;
  39. if (!returning.current || !el) return;
  40. returning.current = false;
  41. if (prefersReducedMotion()) return;
  42. const s = springs.glide();
  43. el.animate(
  44. [
  45. { transform: "translate(-70%, -6%) rotate(-14deg)", opacity: 0 },
  46. { transform: "none", opacity: 1 },
  47. ],
  48. { duration: s.duration, easing: s.easing },
  49. );
  50. }, [order]);
  51. const next = () => {
  52. setOrder((o) => [...o.slice(1), o[0]]);
  53. setSeen((s) => s + 1);
  54. };
  55. const previous = () => {
  56. if (busy.current) return;
  57. returning.current = true;
  58. setOrder((o) => [o[o.length - 1], ...o.slice(0, -1)]);
  59. setSeen((s) => (s - 1 + photos.length) % photos.length);
  60. };
  61. /** Throw the top photo off the deck, then bring the next one up. */
  62. const flyOut = (dx: number, dy: number) => {
  63. const el = topRef.current;
  64. if (!el || busy.current) return;
  65. if (prefersReducedMotion()) {
  66. el.style.transform = "";
  67. next();
  68. return;
  69. }
  70. busy.current = true;
  71. const len = Math.hypot(dx, dy) || 1;
  72. const anim = el.animate(
  73. [
  74. { transform: el.style.transform || "none", opacity: 1 },
  75. {
  76. transform: `translate(${(dx / len) * 560}px, ${(dy / len) * 560}px) rotate(${dx > 0 ? 26 : -26}deg)`,
  77. opacity: 0,
  78. },
  79. ],
  80. {
  81. duration: 360,
  82. easing: "cubic-bezier(.45,0,.85,.4)",
  83. fill: "forwards",
  84. },
  85. );
  86. anim.onfinish = () => {
  87. // The thrown card leaves the visible deck with the reorder and unmounts,
  88. // so its end state holds until then: no flash back on top.
  89. el.style.transform = "";
  90. next();
  91. busy.current = false;
  92. };
  93. };
  94. const onDown = (e: ReactPointerEvent<HTMLDivElement>) => {
  95. if (busy.current || (e.pointerType === "mouse" && e.button !== 0)) return;
  96. e.currentTarget.setPointerCapture(e.pointerId);
  97. gesture.current = {
  98. x: e.clientX,
  99. y: e.clientY,
  100. dx: 0,
  101. dy: 0,
  102. t: e.timeStamp,
  103. v: 0,
  104. };
  105. };
  106. const onMove = (e: ReactPointerEvent<HTMLDivElement>) => {
  107. const g = gesture.current;
  108. const el = topRef.current;
  109. if (!g || !el) return;
  110. const dx = e.clientX - g.x;
  111. const dy = e.clientY - g.y;
  112. g.v = Math.hypot(dx - g.dx, dy - g.dy) / Math.max(1, e.timeStamp - g.t);
  113. g.dx = dx;
  114. g.dy = dy;
  115. g.t = e.timeStamp;
  116. el.style.transform = `translate(${dx}px, ${dy}px) rotate(${dx * 0.05}deg)`;
  117. };
  118. const onUp = () => {
  119. const g = gesture.current;
  120. const el = topRef.current;
  121. gesture.current = null;
  122. if (!g || !el) return;
  123. const dist = Math.hypot(g.dx, g.dy);
  124. if (dist > 90 || g.v > 0.8) {
  125. flyOut(g.dx || 1, g.dy);
  126. return;
  127. }
  128. if (dist < 4) {
  129. flyOut(-1, -0.35);
  130. return;
  131. }
  132. // Not far enough: settle back onto the deck.
  133. const from = el.style.transform;
  134. el.style.transform = "";
  135. if (prefersReducedMotion()) return;
  136. const s = springs.wobble();
  137. el.animate([{ transform: from }, { transform: "none" }], {
  138. duration: s.duration,
  139. easing: s.easing,
  140. });
  141. };
  142. // The browser took the gesture (e.g. a vertical scroll): put the photo back.
  143. const onCancel = () => {
  144. gesture.current = null;
  145. if (topRef.current) topRef.current.style.transform = "";
  146. };
  147. if (!photos.length) return null;
  148. const current = (seen % photos.length) + 1;
  149. return (
  150. <div
  151. className="relative h-full"
  152. onPointerEnter={(e) => e.pointerType !== "touch" && setFanned(true)}
  153. onPointerLeave={() => setFanned(false)}
  154. >
  155. <div className="absolute inset-x-0 top-0 z-20 flex items-center justify-between p-5 sm:p-6">
  156. <p className="font-display text-[17px] font-semibold tracking-[-0.005em]">
  157. {t.title}
  158. </p>
  159. <span className="text-[13px] text-muted tabular-nums">
  160. {t.count(current, photos.length)}
  161. </span>
  162. </div>
  163. <div
  164. className="absolute inset-0 grid place-items-center pt-6"
  165. data-nodrag
  166. >
  167. {order
  168. .slice(0, DEPTH)
  169. .map((photo, i) => ({ photo, i }))
  170. .reverse()
  171. .map(({ photo, i }) => {
  172. const top = i === 0;
  173. const spread = fanned ? (i - 1.2) * 7 : tilt(photo);
  174. return (
  175. <div
  176. key={photo}
  177. ref={top ? topRef : undefined}
  178. className={cn(
  179. "relative col-start-1 row-start-1 aspect-video w-[80%] max-w-[500px] overflow-hidden rounded-2xl bg-card-2 shadow-[0_18px_40px_-18px_rgb(0_0_0/0.55)] ring-1 ring-black/5 select-none [transition:translate_var(--dur-glide)_var(--ease-glide),rotate_var(--dur-glide)_var(--ease-glide),scale_var(--dur-glide)_var(--ease-glide),opacity_.5s_ease] starting:opacity-0",
  180. top
  181. ? "cursor-grab touch-pan-y active:cursor-grabbing"
  182. : "pointer-events-none",
  183. )}
  184. data-cursor={top ? t.fling : undefined}
  185. style={{
  186. zIndex: 10 - i,
  187. translate: fanned
  188. ? `${i * 26}px ${-i * 6}px`
  189. : `${i * 5}px ${-i * 9}px`,
  190. rotate: `${spread}deg`,
  191. scale: String(1 - i * 0.035),
  192. }}
  193. onPointerCancel={top ? onCancel : undefined}
  194. onPointerDown={top ? onDown : undefined}
  195. onPointerMove={top ? onMove : undefined}
  196. onPointerUp={top ? onUp : undefined}
  197. >
  198. <Image
  199. fill
  200. alt={t.alt}
  201. className="pointer-events-none object-cover"
  202. draggable={false}
  203. sizes="(max-width: 640px) 80vw, 480px"
  204. src={photos[photo]}
  205. />
  206. </div>
  207. );
  208. })}
  209. </div>
  210. <div className="absolute right-5 bottom-5 z-20 flex gap-2 sm:right-6 sm:bottom-6">
  211. {([-1, 1] as const).map((dir) => (
  212. <button
  213. key={dir}
  214. aria-label={dir === 1 ? t.next : t.previous}
  215. className="lg grid size-9 place-items-center rounded-full"
  216. type="button"
  217. onClick={() => (dir === 1 ? flyOut(-1, -0.35) : previous())}
  218. >
  219. <span className="lg-caustic" />
  220. <svg
  221. aria-hidden
  222. className={cn("size-4", dir === -1 && "rotate-180")}
  223. fill="none"
  224. viewBox="0 0 16 16"
  225. >
  226. <path
  227. d="M6 3.5 10.5 8 6 12.5"
  228. stroke="currentColor"
  229. strokeLinecap="round"
  230. strokeLinejoin="round"
  231. strokeWidth="1.6"
  232. />
  233. </svg>
  234. </button>
  235. ))}
  236. </div>
  237. </div>
  238. );
  239. }