"use client";
import { AnimatePresence, animate, motion, useMotionValue, useTransform } from "motion/react";
import { useEffect, useId, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from "react";
import { createPortal } from "react-dom";
import { SlideFace } from "./CarouselSlideCard";
import { useIsoLayoutEffect } from "./engine/useCarouselEngine";
import { useFocusTrap } from "./hooks/useFocusTrap";
import { useScrollLock } from "./hooks/useScrollLock";
import { copyVars } from "./portal-vars";
import type { CarouselSlide, RenderImage } from "./types";
/** The morph's spring: a touch softer than the track's snap, so the card visibly travels. */
const MORPH = { type: "spring", stiffness: 210, damping: 28, mass: 1 } as const;
const FADE = { duration: 0.2, ease: "easeOut" } as const;
const CARD_RADIUS = 20;
/** Where an element sits without its own transform (the morph's home), whatever the transform is right now. */
function homeRect(el: HTMLElement | null) {
if (!el) return null;
const prev = el.style.transform;
el.style.transform = "none";
const rect = el.getBoundingClientRect();
el.style.transform = prev;
return rect;
}
const PANEL_RADIUS = 24;
export type CarouselDetailProps = {
slides: CarouselSlide[];
index: number;
aspect: number;
accent?: string;
reduced: boolean;
renderImage?: RenderImage;
/** The active card's face on screen (the morph starts and ends there), unscaled by the carousel's dip. */
cardRect: () => DOMRect | null;
/** The carousel's root: the view takes its fonts and accent from it. */
varsFrom: () => Element | null;
/** Element to focus once the view has closed. */
restoreFocus: () => HTMLElement | null | undefined;
onNavigate: (index: number) => void;
/** Called when the close animation has finished. */
onClosed: () => void;
/** Called when the close animation starts (the carousel behind can start coming back). */
onClosing: () => void;
};
function copyFor(s: CarouselSlide) {
switch (s.kind) {
case "image":
case "video":
return { tag: s.tag, title: s.title ?? s.alt, text: s.description ?? s.caption, href: s.href, cta: s.cta };
case "statement":
return { tag: undefined, title: s.word, text: s.description ?? s.subtitle, href: s.href, cta: s.cta };
case "text":
return { tag: undefined, title: s.title, text: s.description ?? s.body, href: s.href, cta: s.cta };
case "stat":
return { tag: s.delta, title: `${s.value} ${s.label}`, text: s.description, href: s.href, cta: s.cta };
default:
return { tag: undefined, title: s.label ?? "Slide", text: undefined, href: undefined, cta: undefined };
}
}
const Icon = {
close: (
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" aria-hidden>
<path d="m4 4 8 8M12 4l-8 8" />
</svg>
),
prev: (
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
<path d="M13 8H3M7 4 3 8l4 4" />
</svg>
),
next: (
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
<path d="M3 8h10M9 4l4 4-4 4" />
</svg>
),
out: (
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
<path d="M5 11 11 5M6 5h5v5" />
</svg>
),
};
/**
* The detail view. The active card's face flies out of the carousel into the view (a FLIP: the large copy is
* laid out where it belongs, then started from the card's rectangle and sprung home), the copy fades in beside
* it, and closing sends it back to whichever card is active by then. ← / → move through the slides inside.
*/
export function CarouselDetail(props: CarouselDetailProps) {
const { slides, index, aspect, accent, reduced, renderImage, cardRect, varsFrom, restoreFocus, onNavigate, onClosed, onClosing } = props;
const slide = slides[index];
const count = slides.length;
const copy = copyFor(slide);
const titleId = useId();
const box = useRef<HTMLDivElement>(null);
const media = useRef<HTMLDivElement>(null);
const closeBtn = useRef<HTMLButtonElement>(null);
const [phase, setPhase] = useState<"open" | "closing">("open");
const [dir, setDir] = useState(1);
const live = useRef({ closing: false, dragY: 0, pointer: -1, y0: 0, t0: 0 });
// The morph: translate and scale of the media from the card's rectangle to its own, radius kept visually even.
const mx = useMotionValue(0);
const my = useMotionValue(0);
const ms = useMotionValue(1);
const backdrop = useMotionValue(0);
const dragY = useMotionValue(0);
/** The scale the current morph started from: the radius is eased from the card's to the panel's along it. */
const s0 = useMotionValue(1);
const radius = useTransform(() => {
const s = ms.get();
const span = 1 - s0.get();
const t = Math.abs(span) < 0.001 ? 1 : Math.min(1, Math.max(0, (s - s0.get()) / span));
return `${(CARD_RADIUS + (PANEL_RADIUS - CARD_RADIUS) * t) / s}px`;
});
const copyOpacity = useTransform(() => backdrop.get());
useScrollLock(true);
useFocusTrap(box, true, { initial: closeBtn, restore: restoreFocus });
// Open: measure both rectangles before the first paint and start the media on the card.
useIsoLayoutEffect(() => {
copyVars(varsFrom(), box.current);
const to = homeRect(media.current);
const from = cardRect();
if (reduced || !to || !from || !to.width) {
const fade = animate(backdrop, 1, FADE);
return () => fade.stop();
}
const s = from.width / to.width;
s0.jump(s);
mx.jump(from.left - to.left);
my.jump(from.top - to.top);
ms.jump(s);
const runs = [animate(mx, 0, MORPH), animate(my, 0, MORPH), animate(ms, 1, MORPH), animate(backdrop, 1, { duration: 0.35, ease: [0.22, 1, 0.36, 1] })];
return () => runs.forEach((r) => r.stop());
// Runs once, when the view opens.
}, []);
function close() {
if (live.current.closing) return;
live.current.closing = true;
setPhase("closing");
onClosing();
// The media's home includes a swipe-down in progress (the sheet carries it), so it lands where it is dropped.
const home = homeRect(media.current);
const target = cardRect();
const fadeOut = animate(backdrop, 0, { duration: reduced ? 0.2 : 0.3, ease: "easeOut" });
if (reduced || !home || !target || !home.width) {
fadeOut.finished.then(onClosed);
return;
}
const s = target.width / home.width;
// Keep the radius formula pointed the same way: card radius at `s`, panel radius at 1.
s0.jump(s);
const morph = [animate(mx, target.left - home.left, MORPH), animate(my, target.top - home.top, MORPH), animate(ms, s, MORPH)];
Promise.all(morph.map((m) => m.finished)).then(onClosed);
}
function go(delta: number) {
if (live.current.closing) return;
setDir(delta);
onNavigate((index + delta + count) % count);
}
// Keys: Esc closes, ← / → move through the slides (with the carousel behind following along).
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
close();
} else if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
const t = e.target as HTMLElement | null;
if (t?.closest("input, textarea, [contenteditable]")) return;
e.preventDefault();
go(e.key === "ArrowRight" ? 1 : -1);
}
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
});
// Swipe down to close (touch).
const onPointerDown = (e: ReactPointerEvent) => {
if (e.pointerType !== "touch" || live.current.closing) return;
live.current.pointer = e.pointerId;
live.current.y0 = e.clientY;
live.current.t0 = e.timeStamp;
};
const onPointerMove = (e: ReactPointerEvent) => {
if (e.pointerId !== live.current.pointer) return;
const dy = Math.max(0, e.clientY - live.current.y0);
if (box.current && box.current.scrollTop > 0) return;
dragY.set(dy * 0.85);
backdrop.set(Math.max(0.35, 1 - dy / 600));
};
const onPointerUp = (e: ReactPointerEvent) => {
if (e.pointerId !== live.current.pointer) return;
live.current.pointer = -1;
const dy = dragY.get();
const v = dy / Math.max(1, e.timeStamp - live.current.t0);
if (dy > 110 || (dy > 30 && v > 0.6)) close();
else {
animate(dragY, 0, MORPH);
animate(backdrop, 1, FADE);
}
};
const style = { "--dc-aspect": aspect, "--dc-aspect-n": aspect, ...(accent ? { "--dc-accent-now": accent } : {}) } as CSSProperties;
return createPortal(
<div
ref={box}
className="dc-detail"
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
style={style}
data-phase={phase}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
>
<motion.div className="dc-backdrop" style={{ opacity: backdrop }} onClick={close} aria-hidden />
<motion.div className="dc-sheet" style={{ y: dragY }} onClick={(e) => e.target === e.currentTarget && close()}>
<motion.div
ref={media}
className="dc-detail-media"
style={{ x: mx, y: my, scale: ms, borderRadius: radius, ...(reduced ? { opacity: copyOpacity } : {}) }}
>
<AnimatePresence initial={false} custom={dir}>
<motion.div
key={slide.id}
custom={dir}
style={{ position: "absolute", inset: 0, borderRadius: "inherit", overflow: "hidden" }}
initial={reduced ? { opacity: 0 } : { opacity: 0, x: dir * 48 }}
animate={{ opacity: 1, x: 0 }}
exit={reduced ? { opacity: 0 } : { opacity: 0, x: dir * -48 }}
transition={{ duration: 0.42, ease: [0.22, 1, 0.36, 1] }}
>
<SlideFace slide={slide} priority sizes="(min-width: 760px) 560px, 92vw" renderImage={renderImage} panel reduced={reduced} />
</motion.div>
</AnimatePresence>
</motion.div>
<motion.div className="dc-detail-copy" style={{ opacity: copyOpacity }}>
<AnimatePresence initial={false} mode="wait">
<motion.div
key={slide.id}
style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 18 }}
initial={{ opacity: 0, y: reduced ? 0 : 10 }}
animate={{ opacity: 1, y: 0, transition: { duration: 0.4, ease: [0.22, 1, 0.36, 1], delay: 0.05 } }}
exit={{ opacity: 0, y: reduced ? 0 : -6, transition: { duration: 0.15 } }}
>
{copy.tag && <span className="dc-detail-tag">{copy.tag}</span>}
<h2 id={titleId} className="dc-detail-title">
{copy.title}
</h2>
{copy.text && <p className="dc-detail-text">{copy.text}</p>}
</motion.div>
</AnimatePresence>
<div className="dc-detail-meta">
<span className="dc-detail-count" aria-live="polite">
{String(index + 1).padStart(2, "0")} / {String(count).padStart(2, "0")}
</span>
<button type="button" className="dc-btn" aria-label="Previous slide" onClick={() => go(-1)}>
{Icon.prev}
</button>
<button type="button" className="dc-btn" aria-label="Next slide" onClick={() => go(1)}>
{Icon.next}
</button>
{copy.href && (
<a className="dc-detail-cta" href={copy.href}>
{copy.cta ?? "Open"}
{Icon.out}
</a>
)}
</div>
</motion.div>
</motion.div>
<motion.button
ref={closeBtn}
type="button"
className="dc-btn dc-detail-close"
aria-label="Close"
style={{ opacity: copyOpacity }}
onClick={close}
>
{Icon.close}
</motion.button>
</div>,
document.body,
);
}