photo-deck.tsx 7.9 KB

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