跳至正文
获取 Pro
动效组件M.29

手势卡片堆叠

FreeRegistry
components/linyi/swipe-card-stack.tsx
lucide-reactmotion
"use client";
 
import * as React from "react";
import {
AnimatePresence,
motion,
useMotionValue,
useTransform,
type PanInfo,
} from "motion/react";
import { RotateCw } from "lucide-react";
import { cn } from "@/lib/cn";
import { SPRING_SMOOTH, SPRING_SNAPPY } from "@/lib/motion";
import { playSound } from "@/lib/sound";
 
export interface SwipeCardItem {
id: string;
tag: string;
title: string;
detail: string;
accent?: boolean;
}
 
const DEFAULT_CARDS: SwipeCardItem[] = [
{
id: "c1",
tag: "01 · MOTION",
title: "低质量物理弹簧",
detail: "mass 0.3–0.6 与 [0.16, 1, 0.3, 1] 缓动,响应瞬间起速。",
accent: true,
},
{
id: "c2",
tag: "02 · SOUND",
title: "零资产实时合成音效",
detail: "Web Audio API 现场合成钟声、水泡与机械键音,零音频包体。",
},
{
id: "c3",
tag: "03 · ORIENTAL",
title: "素宣与端砚双主题",
detail: "1px 发丝描边与同心圆角,克制强调色保持信息通透。",
},
];
 
export interface SwipeCardStackProps {
cards?: SwipeCardItem[];
threshold?: number;
onCardChange?: (card: SwipeCardItem) => void;
compact?: boolean;
className?: string;
}
 
function DraggableTopCard({
card,
threshold,
compact,
onSwipe,
onKeyDown,
}: {
card: SwipeCardItem;
threshold: number;
compact: boolean;
onSwipe: () => void;
onKeyDown: (e: React.KeyboardEvent<HTMLDivElement>) => void;
}) {
const x = useMotionValue(0);
const rotate = useTransform(x, [-160, 0, 160], [-11, 0, 11]);
const opacity = useTransform(x, [-200, -110, 0, 110, 200], [0.55, 0.92, 1, 0.92, 0.55]);
 
const handleDragEnd = (_: MouseEvent | TouchEvent | PointerEvent, info: PanInfo) => {
if (Math.abs(info.offset.x) >= threshold || Math.abs(info.velocity.x) > 420) {
onSwipe();
}
};
 
return (
<motion.div
drag="x"
dragConstraints={{ left: 0, right: 0 }}
dragElastic={0.85}
onDragEnd={handleDragEnd}
tabIndex={0}
role="group"
aria-roledescription="卡片"
aria-label={`${card.title}:${card.detail}。按左右方向键或空格切换下一张`}
onKeyDown={onKeyDown}
style={{ x, rotate, opacity, zIndex: 30 }}
initial={{ scale: 0.94, y: 12, opacity: 0 }}
animate={{ scale: 1, y: 0, opacity: 1 }}
exit={{ x: 180, rotate: 12, opacity: 0, transition: { duration: 0.2 } }}
transition={SPRING_SMOOTH}
whileTap={{ cursor: "grabbing" }}
className={cn(
"absolute inset-0 flex cursor-grab flex-col justify-between rounded-[16px] border p-4 select-none touch-none outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-canvas",
compact ? "p-3.5" : "p-4"
)}
data-card-id={card.id}
>
<div
className="pointer-events-none absolute inset-0 -z-10 rounded-[16px]"
style={{
background: card.accent ? "var(--bg-inverse)" : "var(--bg-surface)",
border: card.accent ? "1px solid rgba(255,255,255,0.12)" : "1px solid var(--line-strong)",
boxShadow: "var(--elevation-popover)",
}}
/>
<div
className="flex items-center justify-between font-mono-num text-[10px]"
style={{ color: card.accent ? "rgba(245,242,234,0.65)" : "var(--fg-muted)" }}
>
<span>{card.tag}</span>
<span>左右拖拽</span>
</div>
<div className="space-y-1">
<div
className="text-sm font-semibold tracking-tight"
style={{ color: card.accent ? "var(--fg-inverse)" : "var(--fg-primary)" }}
>
{card.title}
</div>
<p
className="text-[11px] leading-relaxed"
style={{ color: card.accent ? "rgba(245,242,234,0.75)" : "var(--fg-secondary)" }}
>
{card.detail}
</p>
</div>
</motion.div>
);
}
 
export function SwipeCardStack({
cards = DEFAULT_CARDS,
threshold = 75,
onCardChange,
compact = false,
className,
}: SwipeCardStackProps) {
const [order, setOrder] = React.useState<SwipeCardItem[]>(cards);
 
const cycle = React.useCallback(() => {
playSound("pop", { pitch: 1.05, volume: 0.7 });
setOrder((prev) => {
if (prev.length <= 1) return prev;
const next = [...prev.slice(1), prev[0]];
if (next[0]) onCardChange?.(next[0]);
return next;
});
}, [onCardChange]);
 
const cyclePrev = React.useCallback(() => {
playSound("pop", { pitch: 0.96, volume: 0.7 });
setOrder((prev) => {
if (prev.length <= 1) return prev;
const next = [prev[prev.length - 1], ...prev.slice(0, -1)];
if (next[0]) onCardChange?.(next[0]);
return next;
});
}, [onCardChange]);
 
const handleCardKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.key === "ArrowRight" || e.key === " " || e.key === "Enter") {
e.preventDefault();
cycle();
} else if (e.key === "ArrowLeft") {
e.preventDefault();
cyclePrev();
}
};
 
const top = order[0];
const rest = order.slice(1, 3);
 
return (
<section
role="region"
aria-roledescription="卡片轮播"
aria-label="可滑动卡片堆叠"
className={cn("flex flex-col items-center gap-3", className)}
>
<span className="sr-only" aria-live="polite">
{top ? `当前卡片:${top.title}` : ""}
</span>
 
<div className={cn("relative", compact ? "h-[124px] w-[224px]" : "h-[146px] w-[268px]")}>
{rest
.slice()
.reverse()
.map((card, revIdx) => {
const depth = rest.length - revIdx;
return (
<motion.div
key={card.id}
aria-hidden="true"
animate={{
scale: 1 - depth * 0.055,
y: depth * 9,
opacity: 1 - depth * 0.22,
}}
transition={SPRING_SMOOTH}
style={{
zIndex: 20 - depth,
background: "var(--bg-surface-2)",
border: "1px solid var(--line-subtle)",
}}
className="pointer-events-none absolute inset-0 rounded-[16px]"
/>
);
})}
 
<AnimatePresence mode="popLayout">
{top && (
<DraggableTopCard
key={top.id}
card={top}
threshold={threshold}
compact={compact}
onSwipe={cycle}
onKeyDown={handleCardKeyDown}
/>
)}
</AnimatePresence>
</div>
 
<motion.button
type="button"
onClick={cycle}
whileTap={{ scale: 0.95 }}
transition={SPRING_SNAPPY}
className="ui-btn ui-btn-default h-7 px-3 text-[11px]"
>
<RotateCw className="h-3 w-3 opacity-70" aria-hidden="true" />
<span>切换下一张</span>
</motion.button>
</section>
);
}