Post Swiper
A deck of social posts you swipe through, card by card.
Customize
<PostSwiper posts={posts} />Changes show live and stay in the address, so a link keeps them.
Code
"use client";
import { useEffect, useState, type CSSProperties, type ReactNode } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import { A11y, Autoplay, EffectCards, Keyboard } from "swiper/modules";
import type { Swiper as SwiperInstance } from "swiper";
import { ArrowLeft, ArrowRight, BadgeCheck, Bookmark, ChartNoAxesColumn, Ellipsis, Globe, Heart, MessageCircle, Repeat2, Send, Share, ThumbsUp } from "lucide-react";
import "swiper/css";
import "swiper/css/effect-cards";
import "swiper/css/a11y";
// A deck of social posts you swipe through. Swiper's "cards" effect does the stacking and the
// drag; the posts are three small card looks (a short-text post, a photo-first post and a
// feed post with actions) so one deck can mix them. Each card has working like and save buttons.
export type SocialPost = {
/** A stable key for the post. */
id: string;
/** Which card look to use: "x" (short text post), "facebook" (feed post) or "instagram" (photo post). */
platform: "x" | "facebook" | "instagram";
/** The author's display name. */
name: string;
/** The author's handle without the @ (used by the "x" look). */
handle?: string;
/** URL of the author's round profile photo. */
avatar: string;
/** When it was posted, as short text: "1h", "Yesterday". */
time: string;
/** Shows the verified badge next to the name. */
verified?: boolean;
/** The post text. */
text?: string;
/** URL of the post's photo. It fills the space the text leaves. */
image?: string;
/** Describes the photo for screen readers. */
imageAlt?: string;
/** Your own picture area in place of `image`: a quote card, a chart, anything. It fills the same space. */
media?: ReactNode;
/** The like count. The like button adds one. */
likes?: number;
/** The comment count. */
comments?: number;
/** The share or repost count. */
shares?: number;
};
export type PostSwiperProps = {
/** The posts, front card first. Four to ten work best. */
posts: SocialPost[];
/** Wraps around: the last card is followed by the first. Needs at least three posts. */
loop?: boolean;
/** Shows a grab cursor over the deck. */
grabCursor?: boolean;
/** Seconds between automatic swipes. 0 turns autoplay off. It pauses while the pointer is over the deck. */
autoplayDelay?: number;
/** How much each card behind the front one is turned, in degrees. */
tilt?: number;
/** How far each card behind the front one sits out from it, in pixels. */
spread?: number;
/** Darkens the cards behind the front one, for depth. */
shadows?: boolean;
/** Card colours: "dark" or "light". */
appearance?: "dark" | "light";
/** The card width in pixels. It shrinks to fit a narrow screen. */
cardWidth?: number;
/** Card width divided by card height. Lower is taller. */
cardRatio?: number;
/** Shows the arrow buttons and the counter under the deck. */
showNav?: boolean;
/** The name screen readers give the deck. */
label?: string;
/** Extra classes for the outer box. */
className?: string;
/** Extra classes for each card, e.g. a different radius. */
cardClassName?: string;
};
// Colours of the two card looks. The card reads them as CSS variables, so a change here is the only edit.
const palettes: Record<NonNullable<PostSwiperProps["appearance"]>, CSSProperties> = {
dark: { "--pc-bg": "#202224", "--pc-text": "#f1f2f3", "--pc-muted": "#9ea3a9", "--pc-line": "rgba(255,255,255,0.1)", "--pc-hover": "rgba(255,255,255,0.07)" } as CSSProperties,
light: { "--pc-bg": "#ffffff", "--pc-text": "#14171a", "--pc-muted": "#667078", "--pc-line": "rgba(20,23,26,0.12)", "--pc-hover": "rgba(20,23,26,0.06)" } as CSSProperties,
};
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
const full = new Intl.NumberFormat("en");
// A quick scale pop on the icon that was pressed. The Web Animations API cleans itself up and
// needs no library. Skipped when the visitor prefers reduced motion.
function pop(element: Element | null) {
if (!element || typeof element.animate !== "function") return;
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
element.animate([{ transform: "scale(1)" }, { transform: "scale(1.35)" }, { transform: "scale(1)" }], { duration: 320, easing: "cubic-bezier(0.34, 1.56, 0.64, 1)" });
}
export function PostSwiper({
posts,
loop = true,
grabCursor = true,
autoplayDelay = 0,
tilt = 2,
spread = 10,
shadows = true,
appearance = "dark",
cardWidth = 380,
cardRatio = 0.74,
showNav = true,
label = "Social posts",
className = "",
cardClassName = "",
}: PostSwiperProps) {
const [swiper, setSwiper] = useState<SwiperInstance | null>(null);
const [active, setActive] = useState(0);
const [reduced, setReduced] = useState(false);
// Reduced motion is read after mount, so the server and the first client render match
useEffect(() => {
const query = window.matchMedia("(prefers-reduced-motion: reduce)");
const update = () => setReduced(query.matches);
update();
query.addEventListener("change", update);
return () => query.removeEventListener("change", update);
}, []);
// Swiper reads the card effect options once, so after a change we hand it the new ones and redraw
useEffect(() => {
if (!swiper || swiper.destroyed) return;
Object.assign(swiper.params.cardsEffect ?? {}, { perSlideRotate: tilt, perSlideOffset: spread, slideShadows: shadows });
swiper.update();
}, [swiper, tilt, spread, shadows]);
// Autoplay starts and stops from the props (and never runs for visitors who prefer less motion)
const autoplayOn = autoplayDelay > 0 && !reduced;
useEffect(() => {
if (!swiper || swiper.destroyed || !swiper.autoplay) return;
if (autoplayOn) {
swiper.params.autoplay = { ...(swiper.params.autoplay as object), delay: autoplayDelay * 1000, disableOnInteraction: false, pauseOnMouseEnter: true };
swiper.autoplay.start();
} else {
swiper.autoplay.stop();
}
}, [swiper, autoplayOn, autoplayDelay]);
// Only the front card can take focus. The cards behind it (and the loop's duplicates) are inert,
// so tabbing never lands on a button you can't see.
const markFront = (instance: SwiperInstance) => {
instance.slides.forEach((slide) => slide.toggleAttribute("inert", !slide.classList.contains("swiper-slide-active")));
};
const canLoop = loop && posts.length > 2;
const go = (direction: 1 | -1) => {
if (!swiper || swiper.destroyed) return;
if (direction === 1) swiper.slideNext();
else swiper.slidePrev();
};
return (
<div
role="region"
aria-roledescription="carousel"
aria-label={label}
className={`flex w-full flex-col items-center gap-7 ${className}`}
>
{/* Remounted when loop changes, because Swiper builds its loop copies once */}
<Swiper
key={String(canLoop)}
modules={[EffectCards, Keyboard, A11y, Autoplay]}
effect="cards"
cardsEffect={{ slideShadows: shadows, perSlideRotate: tilt, perSlideOffset: spread }}
grabCursor={grabCursor}
loop={canLoop}
speed={reduced ? 0 : 500}
keyboard={{ enabled: true, onlyInViewport: true }}
a11y={{ enabled: true }}
autoplay={{ delay: Math.max(autoplayDelay, 1) * 1000, disableOnInteraction: false, pauseOnMouseEnter: true }}
onSwiper={(instance) => {
setSwiper(instance);
setActive(instance.realIndex);
markFront(instance);
// Autoplay begins on its own; the effect above turns it off when the prop says so
if (!autoplayOn) instance.autoplay?.stop();
}}
onDestroy={() => setSwiper(null)}
onRealIndexChange={(instance) => setActive(instance.realIndex)}
onSlideChange={markFront}
onTransitionEnd={markFront}
onSlidesUpdated={markFront}
className="!overflow-visible"
style={{ width: cardWidth, maxWidth: "100%", aspectRatio: String(cardRatio), margin: 0 }}
>
{posts.map((post) => (
<SwiperSlide key={post.id} className={`!rounded-[1.6rem] bg-transparent shadow-[0_30px_60px_-30px_rgba(0,0,0,0.55)] ${cardClassName}`}>
<PostCard post={post} appearance={appearance} />
</SwiperSlide>
))}
</Swiper>
{showNav && (
<div className="flex items-center gap-4 font-mono text-[12px] tracking-[0.12em] uppercase tabular-nums">
<NavButton label="Previous post" onClick={() => go(-1)}>
<ArrowLeft size={16} aria-hidden="true" />
</NavButton>
<span aria-hidden="true" className="min-w-[5.5ch] text-center opacity-70">
{String(active + 1).padStart(2, "0")} / {String(posts.length).padStart(2, "0")}
</span>
<NavButton label="Next post" onClick={() => go(1)}>
<ArrowRight size={16} aria-hidden="true" />
</NavButton>
</div>
)}
</div>
);
}
function NavButton({ label, onClick, children }: { label: string; onClick: () => void; children: ReactNode }) {
return (
<button
type="button"
aria-label={label}
onClick={onClick}
className="grid size-10 cursor-pointer place-items-center rounded-full border border-current/25 transition-[background-color,transform] duration-200 hover:bg-current/10 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current active:scale-95"
>
{children}
</button>
);
}
// ---------------------------------------------------------------------------------------------
// The card. Everything inside is sized in em, and the card sets its own font size from its width
// (a container query), so the same post reads well at 330px and at 420px.
// ---------------------------------------------------------------------------------------------
function PostCard({ post, appearance }: { post: SocialPost; appearance: NonNullable<PostSwiperProps["appearance"]> }) {
return (
<div className="h-full" style={{ containerType: "inline-size" }}>
<article
className="flex h-full flex-col overflow-hidden rounded-[inherit] border border-[color:var(--pc-line)] bg-[var(--pc-bg)] text-[color:var(--pc-text)] select-none"
style={{ ...palettes[appearance], fontSize: "clamp(12.5px, 4cqw, 16px)", fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif' }}
>
{post.platform === "x" && <ShortPost post={post} />}
{post.platform === "facebook" && <FeedPost post={post} />}
{post.platform === "instagram" && <PhotoPost post={post} />}
</article>
</div>
);
}
function Avatar({ post, className = "" }: { post: SocialPost; className?: string }) {
// The name sits right beside it, so the photo is decoration
return <img src={post.avatar} alt="" draggable={false} loading="lazy" className={`size-[2.9em] shrink-0 rounded-full object-cover ${className}`} />;
}
function Picture({ post, className = "" }: { post: SocialPost; className?: string }) {
if (!post.media && !post.image) return null;
return (
<div className={`relative min-h-0 flex-1 overflow-hidden ${className}`}>
{post.media ?? (
<img src={post.image} alt={post.imageAlt ?? ""} draggable={false} loading="lazy" decoding="async" className="absolute inset-0 h-full w-full object-cover" />
)}
</div>
);
}
function Name({ post }: { post: SocialPost }) {
return (
<span className="flex min-w-0 items-center gap-[0.3em]">
<span className="truncate font-bold">{post.name}</span>
{post.verified && <BadgeCheck aria-label="Verified" size="1.2em" strokeWidth={2.2} className="shrink-0 fill-[#1d9bf0] text-[var(--pc-bg)]" />}
</span>
);
}
// A small round or pill button. `on` tints it with `colour` and keeps it pressed.
function Action({ label, text, count, on = false, colour, onPress, children, className = "" }: { label: string; text?: string; count?: number; on?: boolean; colour?: string; onPress?: (icon: HTMLElement | null) => void; children: ReactNode; className?: string }) {
return (
<button
type="button"
aria-label={label}
aria-pressed={onPress ? on : undefined}
onClick={(event) => onPress?.(event.currentTarget.querySelector<HTMLElement>("[data-icon]"))}
style={on && colour ? { color: colour } : undefined}
className={`group flex cursor-pointer items-center gap-[0.45em] rounded-full p-[0.5em] text-[color:var(--pc-muted)] transition-colors duration-200 hover:bg-[var(--pc-hover)] hover:text-[color:var(--pc-text)] focus-visible:outline-2 focus-visible:outline-[#1d9bf0] ${className}`}
>
<span data-icon className="grid place-items-center">
{children}
</span>
{text && <span className="text-[0.92em] font-semibold">{text}</span>}
{count !== undefined && <span className="text-[0.88em] tabular-nums">{compact.format(count)}</span>}
</button>
);
}
// The short-text look: avatar beside a header, big type when there is no picture, a stats row below.
function ShortPost({ post }: { post: SocialPost }) {
const [liked, setLiked] = useState(false);
const [reposted, setReposted] = useState(false);
const [saved, setSaved] = useState(false);
const hasPicture = Boolean(post.image || post.media);
return (
<div className="flex h-full flex-col gap-[0.8em] p-[1.1em] pb-[0.6em]">
<header className="flex items-center gap-[0.75em]">
<Avatar post={post} />
<div className="flex min-w-0 flex-1 flex-col leading-tight">
<Name post={post} />
<span className="truncate text-[0.9em] text-[color:var(--pc-muted)]">
@{post.handle ?? post.name.toLowerCase().replace(/\s+/g, "")} · {post.time}
</span>
</div>
<Ellipsis size="1.4em" aria-hidden="true" className="text-[color:var(--pc-muted)]" />
</header>
{post.text && (
<p className={`whitespace-pre-wrap break-words ${hasPicture ? "text-[1em] leading-[1.45]" : "my-auto text-[1.6em] leading-[1.22] font-medium tracking-[-0.015em]"}`}>{post.text}</p>
)}
<Picture post={post} className="rounded-[1em] border border-[color:var(--pc-line)]" />
<div className="-mx-[0.5em] mt-auto flex items-center justify-between">
<Action label="Reply" count={post.comments}>
<MessageCircle size="1.35em" aria-hidden="true" />
</Action>
<Action label="Repost" count={(post.shares ?? 0) + (reposted ? 1 : 0)} on={reposted} colour="#00ba7c" onPress={(icon) => { setReposted(!reposted); if (!reposted) pop(icon); }}>
<Repeat2 size="1.4em" aria-hidden="true" />
</Action>
<Action label="Like" count={(post.likes ?? 0) + (liked ? 1 : 0)} on={liked} colour="#f91880" onPress={(icon) => { setLiked(!liked); if (!liked) pop(icon); }}>
<Heart size="1.3em" aria-hidden="true" fill={liked ? "currentColor" : "none"} />
</Action>
<Action label="Views">
<ChartNoAxesColumn size="1.35em" aria-hidden="true" />
</Action>
<Action label="Save" on={saved} colour="#1d9bf0" onPress={(icon) => { setSaved(!saved); if (!saved) pop(icon); }}>
<Bookmark size="1.3em" aria-hidden="true" fill={saved ? "currentColor" : "none"} />
</Action>
</div>
</div>
);
}
// The feed look: header row, text, a full-width picture, a reactions line and three wide buttons.
function FeedPost({ post }: { post: SocialPost }) {
const [liked, setLiked] = useState(false);
const hasPicture = Boolean(post.image || post.media);
const likes = (post.likes ?? 0) + (liked ? 1 : 0);
return (
<div className="flex h-full flex-col">
<header className="flex items-center gap-[0.7em] p-[0.9em] pb-[0.7em]">
<Avatar post={post} className="size-[2.7em]" />
<div className="flex min-w-0 flex-1 flex-col leading-tight">
<Name post={post} />
<span className="flex items-center gap-[0.35em] text-[0.82em] text-[color:var(--pc-muted)]">
{post.time} · <Globe size="1em" aria-label="Public" />
</span>
</div>
<Ellipsis size="1.4em" aria-hidden="true" className="text-[color:var(--pc-muted)]" />
</header>
{post.text && (
<p className={`px-[0.95em] break-words whitespace-pre-wrap ${hasPicture ? "pb-[0.8em] text-[0.97em] leading-[1.45]" : "my-auto pb-[0.8em] text-[1.55em] leading-[1.25] font-medium tracking-[-0.015em]"}`}>{post.text}</p>
)}
<Picture post={post} />
<div className="flex items-center justify-between px-[0.95em] pt-[0.7em] pb-[0.5em] text-[0.86em] text-[color:var(--pc-muted)]">
<span className="flex items-center gap-[0.5em]">
<span className="grid size-[1.7em] place-items-center rounded-full bg-[#1877f2] text-white">
<ThumbsUp size="0.95em" fill="currentColor" aria-hidden="true" />
</span>
<span className="tabular-nums">{full.format(likes)}</span>
</span>
<span className="tabular-nums">
{full.format(post.comments ?? 0)} comments · {full.format(post.shares ?? 0)} shares
</span>
</div>
<div className="mx-[0.95em] mb-[0.5em] grid grid-cols-3 gap-[0.3em] border-t border-[color:var(--pc-line)] pt-[0.4em]">
<Action label="Like" text="Like" on={liked} colour="#1877f2" onPress={(icon) => { setLiked(!liked); if (!liked) pop(icon); }} className="justify-center rounded-[0.6em]">
<ThumbsUp size="1.25em" aria-hidden="true" fill={liked ? "currentColor" : "none"} />
</Action>
<Action label="Comment" text="Comment" className="justify-center rounded-[0.6em]">
<MessageCircle size="1.25em" aria-hidden="true" />
</Action>
<Action label="Share" text="Share" className="justify-center rounded-[0.6em]">
<Share size="1.25em" aria-hidden="true" />
</Action>
</div>
</div>
);
}
// The photo look: a ringed avatar, the picture taking most of the card, actions and a caption.
function PhotoPost({ post }: { post: SocialPost }) {
const [liked, setLiked] = useState(false);
const [saved, setSaved] = useState(false);
const likes = (post.likes ?? 0) + (liked ? 1 : 0);
return (
<div className="flex h-full flex-col">
<header className="flex items-center gap-[0.7em] p-[0.8em]">
{/* The gradient ring is the avatar's padding showing through */}
<span className="rounded-full bg-[conic-gradient(from_200deg,#ffcb03,#e6683c,#dc2743,#cc2366,#d300c5,#ffcb03)] p-[2px]">
<Avatar post={post} className="size-[2.5em] border-2 border-[var(--pc-bg)]" />
</span>
<div className="flex min-w-0 flex-1 items-center gap-[0.4em] text-[0.95em] leading-tight">
<Name post={post} />
<span className="text-[color:var(--pc-muted)]">· {post.time}</span>
</div>
<Ellipsis size="1.4em" aria-hidden="true" className="text-[color:var(--pc-muted)]" />
</header>
<Picture post={post} />
<div className="flex items-center gap-[0.1em] px-[0.5em] pt-[0.45em]">
<Action label="Like" on={liked} colour="#ef4444" onPress={(icon) => { setLiked(!liked); if (!liked) pop(icon); }} className="text-[color:var(--pc-text)]">
<Heart size="1.65em" aria-hidden="true" fill={liked ? "currentColor" : "none"} />
</Action>
<Action label="Comment" className="text-[color:var(--pc-text)]">
<MessageCircle size="1.55em" aria-hidden="true" />
</Action>
<Action label="Send" className="text-[color:var(--pc-text)]">
<Send size="1.5em" aria-hidden="true" />
</Action>
<Action label="Save" on={saved} onPress={(icon) => { setSaved(!saved); if (!saved) pop(icon); }} className="ml-auto text-[color:var(--pc-text)]">
<Bookmark size="1.55em" aria-hidden="true" fill={saved ? "currentColor" : "none"} />
</Action>
</div>
<div className="px-[0.95em] pt-[0.1em] pb-[0.9em] text-[0.93em] leading-[1.4]">
<p className="font-bold tabular-nums">{full.format(likes)} likes</p>
{post.text && (
<p className="mt-[0.15em] line-clamp-2">
<span className="font-bold">{post.name}</span> {post.text}
</p>
)}
</div>
</div>
);
}
The component. Installs to components/dimaac/post-swiper.tsx.
Install
With the shadcn CLI
npx shadcn@latest add https://ui.dimaac.com/r/post-swiper.jsonIt adds components/dimaac/post-swiper.tsx and installs what it imports. With the @dimaac namespace in components.json (Docs) it's just npx shadcn@latest add @dimaac/post-swiper.
By hand
npm install swiper lucide-react- Install the packages it uses: swiper, lucide-react.
- Copy the component file below into components/dimaac/post-swiper.tsx.
- It's styled with Tailwind v4 classes. If that folder sits outside the places Tailwind scans, add it with @source in your CSS.
- Import it with import { PostSwiper } from "@/components/dimaac/post-swiper". Give its parent a size: it fills it.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
posts (required) | SocialPost[] | - | The posts, front card first. Four to ten work best. |
loop | boolean | true | Wraps around: the last card is followed by the first. Needs at least three posts. |
grabCursor | boolean | true | Shows a grab cursor over the deck. |
autoplayDelay | number | 0 | Seconds between automatic swipes. 0 turns autoplay off. It pauses while the pointer is over the deck. |
tilt | number | 2 | How much each card behind the front one is turned, in degrees. |
spread | number | 10 | How far each card behind the front one sits out from it, in pixels. |
shadows | boolean | true | Darkens the cards behind the front one, for depth. |
appearance | "dark" | "light" | "dark" | Card colours: "dark" or "light". |
cardWidth | number | 380 | The card width in pixels. It shrinks to fit a narrow screen. |
cardRatio | number | 0.74 | Card width divided by card height. Lower is taller. |
showNav | boolean | true | Shows the arrow buttons and the counter under the deck. |
label | string | "Social posts" | The name screen readers give the deck. |
className | string | "" | Extra classes for the outer box. |
cardClassName | string | "" | Extra classes for each card, e.g. a different radius. |
Use with AI
Agent prompt
Paste it into Claude Code, Cursor or any coding agent, or open it straight in a chat. It carries your Customize settings.
Add the Post Swiper component (<PostSwiper />) from DiMaac UI to this project.
Docs: https://ui.dimaac.com/components/post-swiper
Source and dependencies (shadcn registry JSON): https://ui.dimaac.com/r/post-swiper.json
Install it with:
npx shadcn@latest add https://ui.dimaac.com/r/post-swiper.json
Then use it like this:
import { PostSwiper } from "@/components/dimaac/post-swiper";
<PostSwiper posts={posts} />
If the shadcn CLI isn't set up here, fetch the registry JSON above, write files[0].content to components/dimaac/post-swiper.tsx and install swiper, lucide-react.
It uses Tailwind v4 classes, so make sure Tailwind scans that folder. Give its parent a size: it fills it. Keep light and dark mode working and keep its prefers-reduced-motion fallback.
Full index for agents: https://ui.dimaac.com/llms.txtFiles agents read
- llms.txt
- Every component and how to install it
- post-swiper.md
- This page as Markdown: install, props and the full source
- post-swiper.json
- The shadcn registry item
About
A stack of social post cards that you drag away one by one, built on Swiper's cards effect. It ships three card looks (a short-text post, a feed post and a photo post) that mix freely in one deck, and any post can bring its own picture area for quote cards or charts. Like, repost and save buttons work and pop. It loops, drifts on its own if you ask, answers the arrow keys, follows a finger on touch screens, and only lets the front card take focus so tabbing never lands on a hidden button. Card colours switch between dark and light, the cards scale with their width, and reduced motion turns off autoplay and the slide animation. Ported from the first DiMaac UI and reworked so it takes plain post data instead of ready-made elements.
- Installs to
components/dimaac/post-swiper.tsx- Uses
- swiper, lucide-react
- Tags
- swiper, cards, social, posts, stack, drag
Photo by Benginur Hajjaj, rena, Amino, Steph Meade, Lloyd Creates, Amino, Viri Gutiérrez, Beth Design Studio, Dona Mara, Ricardo Matos and Krystyna on Lummi (Lummi License).