← Components

Postcard Word

A word in a sentence that opens a stack of photos you flip through like postcards.

Text · FreeInstall ↓
Open preview ↗
Loading the demoNew tab ↗

Customize

156 px
-2 deg
#ffffff
Your code
<PostcardWord children={children} photos={photos} />

Changes show live and stay in the address, so a link keeps them.

Code

"use client";

import { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type FocusEvent, type PointerEvent, type ReactNode } from "react";

// A word in a sentence with a small stack of postcards behind it. Point at the word (or tab to it) and the stack rises
// above it; click it and the card peeking out behind pops like toast: it dips for a split second, springs up from
// behind the front card, slows under gravity until it is clear, swaps in front at the top of its arc, drops back onto
// the stack and lands with a little weight. Then the next card slides out from behind. On touch, a tap opens the stack
// and the next tap pops a card.

export type PostcardWordProps = {
  /** The word in the sentence, e.g. "outside". */
  children: ReactNode;
  /** The photos in the stack (image URLs), in the order they pop up. With one photo it is a single card. They are
   *  decoration: screen readers hear only the word. */
  photos: string[];
  /** The width of each photo in px. */
  width?: number;
  /** The photo's width divided by its height: 1.5 for landscape, 1 for a square portrait. */
  ratio?: number;
  /** The stack's tilt, in degrees. */
  tilt?: number;
  /** Whether the stack opens above or below the word. */
  side?: "top" | "bottom";
  /** The colour of each card's frame. */
  frame?: string;
  /** Called when the stack opens or closes, e.g. to dim the rest of the sentence. */
  onOpenChange?: (open: boolean) => void;
  /** Extra classes around the word, e.g. its colour. The word inherits them. */
  className?: string;
};

const PAD = 5; // the white frame around each photo
const PEEK = { x: 10, y: -9, r: 6, s: 0.95 }; // the card waiting behind (keep in sync with .pw-card.is-next)
const TUCK = { x: -2, y: 2, r: 0, s: 0.96 }; // fully hidden behind the front card
const LOAD = 0.06; // seconds of the small dip before it springs out
const LOAD_DIP = 2;
const RISE = 0.22; // seconds from launch to the top of the arc
const SETTLE = 0.3; // seconds of landing after it touches down
const PEEK_OUT = 320; // ms for the next card to slide out from behind

type Pose = { x: number; y: number; r: number; s: number };
const pose = (p: Pose) => `translate(${p.x.toFixed(2)}px, ${p.y.toFixed(2)}px) rotate(${p.r.toFixed(3)}deg) scale(${p.s.toFixed(4)})`;

type Flight = { frames: Keyframe[]; duration: number; landAt: number };
const flights = new Map<number, Flight>();

// Worked out once per card height: a dip, a throw straight up with gravity chosen so it stops just clear of the front
// card, a free fall onto the stack, then a stiff, well damped spring for the landing so it settles in one soft dip
function flightFor(card: number): Flight {
  const known = flights.get(card);
  if (known) return known;
  const apex = -(card + 10);
  // The higher the card, the softer and fainter its shadow, like a real one lifting off the table
  const shadow = (lift: number) => {
    const fade = Math.max(0, 1 - lift / (card + 6));
    return `0 0 0 1px rgb(0 0 0 / 0.07), 0 ${(16 + lift * 0.12).toFixed(1)}px ${(32 + lift * 0.25).toFixed(1)}px -16px rgb(0 0 0 / ${(0.28 * fade).toFixed(3)})`;
  };
  const start = PEEK.y + LOAD_DIP;
  const gravity = (2 * (start - apex)) / (RISE * RISE);
  const fall = Math.sqrt((2 * -apex) / gravity);
  const top = LOAD + RISE;
  const landAt = top + fall;
  const duration = landAt + SETTLE;
  const stiffness = (2 * Math.PI * 3.4) ** 2;
  const damping = 2 * 0.62 * Math.sqrt(stiffness);
  const landTilt = 0.8;
  let dip = 0;
  let dipSpeed = gravity * fall * 0.16; // the stack gives a little under the landing card
  let tilt = landTilt;
  let tiltSpeed = (landTilt + 3) / fall; // keep the spin it had in the air
  let springTime = landAt;
  const frames: Keyframe[] = [];
  const count = Math.ceil(duration * 60);

  for (let i = 0; i <= count; i++) {
    const t = Math.min(duration, i / 60);
    let x = PEEK.x;
    let y: number;
    let r: number;
    let s: number;
    let lift: number;

    if (t <= LOAD) {
      const u = t / LOAD;
      y = PEEK.y + LOAD_DIP * Math.sin((Math.PI / 2) * u);
      r = PEEK.r;
      s = PEEK.s;
      lift = 0;
    } else if (t <= top) {
      const tr = t - LOAD;
      const u = tr / RISE;
      const ease = u * (2 - u);
      y = start - gravity * RISE * tr + 0.5 * gravity * tr * tr;
      r = PEEK.r + (-3 - PEEK.r) * ease;
      s = PEEK.s + (1 - PEEK.s) * ease;
      x = PEEK.x * (1 - (t - LOAD) / (landAt - LOAD));
      lift = Math.max(0, PEEK.y - y);
    } else if (t <= landAt) {
      const u = (t - top) / fall;
      y = apex + 0.5 * gravity * (t - top) ** 2;
      r = -3 + (landTilt + 3) * u;
      s = 1 + 0.015 * Math.sin(Math.PI * u);
      x = PEEK.x * (1 - (t - LOAD) / (landAt - LOAD));
      lift = Math.max(0, -y);
    } else {
      // Step the landing spring forward in small slices for a stable settle
      while (springTime < t) {
        const step = Math.min(1 / 480, t - springTime);
        dipSpeed += (-stiffness * dip - damping * dipSpeed) * step;
        dip += dipSpeed * step;
        tiltSpeed += (-stiffness * tilt - damping * tiltSpeed) * step;
        tilt += tiltSpeed * step;
        springTime += step;
      }
      x = 0;
      y = dip;
      r = tilt;
      s = 1 - 0.02 * Math.max(0, dip / 6);
      lift = 0;
    }

    frames.push({
      offset: t / duration,
      transform: i === count ? "none" : pose({ x, y, r, s }),
      boxShadow: shadow(lift),
      zIndex: t < top ? 2 : 4,
    });
  }

  const made = { frames, duration: duration * 1000, landAt: landAt * 1000 };
  flights.set(card, made);
  return made;
}

/** The stack's state and the pop. Exported so a page can drive several words' stacks its own way. */
export function usePostcards(count: number, card: number) {
  const [photo, setPhoto] = useState(0);
  const current = useRef(0);
  const cards = useRef<(HTMLElement | null)[]>([]);
  const running = useRef<Animation[]>([]);
  const busy = useRef(false);
  const queued = useRef(false);

  const pop = useCallback(() => {
    if (count < 2) return;
    if (busy.current) {
      queued.current = true;
      return;
    }
    const top = current.current;
    const next = (top + 1) % count;
    const after = (top + 2) % count;

    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
      setPhoto(next);
      return;
    }

    const front = cards.current[top];
    const incoming = cards.current[next];
    const waiting = cards.current[after];
    if (!front || !incoming || !waiting) return;

    busy.current = true;
    const { frames, duration, landAt } = flightFor(card);
    const throwCard = incoming.animate(frames, { duration, easing: "linear", fill: "forwards" });

    // The front card gives a touch as the one behind springs off
    const press = front.animate([{ transform: "none" }, { transform: "translateY(1.5px)", offset: 0.45 }, { transform: "none" }], { duration: 170, easing: "ease-in-out" });

    // The next card waits tucked right behind the front card, then slides out into the peek spot. With two
    // postcards that card is the old front one, so it starts from where it already is.
    const tucked = after === top;
    const slideOut = waiting.animate(
      [
        { transform: tucked ? "none" : pose(TUCK), opacity: 1, zIndex: tucked ? 3 : 1 },
        { transform: pose(PEEK), opacity: 1, zIndex: tucked ? 3 : 1 },
      ],
      { delay: landAt - 30, duration: PEEK_OUT, easing: "cubic-bezier(0.3, 0.7, 0.2, 1)", fill: "both" },
    );
    running.current = [throwCard, press, slideOut];

    Promise.all([throwCard.finished, slideOut.finished])
      .then(() => setPhoto(next))
      .catch(() => {
        running.current.forEach((animation) => animation.cancel());
        running.current = [];
        busy.current = false;
        queued.current = false;
      });
  }, [count, card]);

  // Once the new order is on the page, drop the finished animations so the resting styles take over seamlessly
  useLayoutEffect(() => {
    current.current = photo;
    running.current.forEach((animation) => animation.cancel());
    running.current = [];
    busy.current = false;
    if (queued.current) {
      queued.current = false;
      pop();
    }
  }, [photo, pop]);

  // Stop any flight if the word goes away mid-air
  useEffect(() => {
    const animations = running;
    return () => animations.current.forEach((animation) => animation.cancel());
  }, []);

  const place = (index: number) => {
    if (index === photo) return "is-top";
    if (index === (photo + 1) % count) return "is-next";
    return "is-rest";
  };

  const setCard = (index: number) => (node: HTMLElement | null) => {
    cards.current[index] = node;
  };

  return { photo, place, pop, setCard };
}

export function PostcardWord({ children, photos, width = 156, ratio = 1.5, tilt = -2, side = "top", frame = "#fff", onOpenChange, className = "" }: PostcardWordProps) {
  const list = photos;
  const height = Math.round(width / ratio);
  const [open, setOpen] = useState(false);
  const wrap = useRef<HTMLSpanElement>(null);
  const postcards = usePostcards(list.length, height + PAD * 2);
  const sources = list.join("\n");

  // Warm the other photos so each one pops up without a blank frame
  useEffect(() => {
    sources
      .split("\n")
      .slice(1)
      .forEach((src) => {
        new Image().src = src;
      });
  }, [sources]);

  // Tell the page, so it can dim the rest of the sentence while the stack is up
  const told = useRef(false);
  useEffect(() => {
    if (!told.current && !open) return;
    told.current = true;
    onOpenChange?.(open);
  }, [open, onOpenChange]);

  // On a touch screen a tap opens the stack and a tap anywhere else closes it
  useEffect(() => {
    if (!open) return;
    const close = (event: globalThis.PointerEvent) => {
      if (!(event.target instanceof Node) || !wrap.current?.contains(event.target)) setOpen(false);
    };
    document.addEventListener("pointerdown", close);
    return () => document.removeEventListener("pointerdown", close);
  }, [open]);

  const enter = (event: PointerEvent) => {
    if (event.pointerType !== "touch") setOpen(true);
  };
  const leave = (event: PointerEvent) => {
    if (event.pointerType !== "touch") setOpen(false);
  };
  // Keyboard focus opens the stack; a click or tap is handled by onClick instead
  const focus = (event: FocusEvent<HTMLButtonElement>) => {
    if (event.currentTarget.matches(":focus-visible")) setOpen(true);
  };

  return (
    <span ref={wrap} className={`pw ${className}`} style={{ "--pw-w": `${width}px`, "--pw-h": `${height}px`, "--pw-tilt": `${tilt}deg`, "--pw-frame": frame } as CSSProperties}>
      <style href="dimaac-postcard-word" precedence="default">
        {css}
      </style>
      <button
        type="button"
        className={`pw-word ${open ? "is-active" : ""}`}
        onPointerEnter={enter}
        onPointerLeave={leave}
        onFocus={focus}
        onBlur={() => setOpen(false)}
        onKeyDown={(event) => event.key === "Escape" && setOpen(false)}
        onClick={() => {
          if (open) postcards.pop();
          setOpen(true);
        }}
      >
        {children}
      </button>
      <span aria-hidden="true" className={`pw-stack pw-${side} ${open ? "is-open" : ""}`}>
        {list.map((src, index) => (
          <span key={`${src}-${index}`} ref={postcards.setCard(index)} className={`pw-card ${postcards.place(index)}`}>
            <img src={src} alt="" draggable={false} />
          </span>
        ))}
      </span>
    </span>
  );
}

const css = `
.pw {
  --pw-spring: cubic-bezier(0.34, 1.56, 0.64, 1);
  position: relative;
  display: inline-block;
}
.pw-word {
  position: relative;
  padding: 0;
  border: 0;
  background: none;
  font: inherit;
  color: inherit;
  cursor: pointer;
  text-decoration: underline dotted;
  text-decoration-color: color-mix(in srgb, currentColor 32%, transparent);
  text-underline-offset: 4px;
  transition: color 0.3s, text-decoration-color 0.2s;
}
.pw-word:hover,
.pw-word.is-active {
  text-decoration-color: currentColor;
}
.pw-stack {
  position: absolute;
  left: 50%;
  z-index: 5;
  width: calc(var(--pw-w) + ${PAD * 2}px);
  height: calc(var(--pw-h) + ${PAD * 2}px);
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s ease, transform 0.55s var(--pw-spring);
}
.pw-top {
  bottom: calc(100% + 10px);
  transform: translate(-50%, 8px) scale(0.94) rotate(var(--pw-tilt));
}
.pw-bottom {
  top: calc(100% + 10px);
  transform: translate(-50%, -8px) scale(0.94) rotate(var(--pw-tilt));
}
.pw-stack.is-open {
  opacity: 1;
  transform: translate(-50%, 0) scale(1) rotate(var(--pw-tilt));
}
.pw-card {
  position: absolute;
  inset: 0;
  padding: ${PAD}px;
  border-radius: 14px;
  background: var(--pw-frame);
  box-shadow: 0 0 0 1px rgb(0 0 0 / 0.07), 0 16px 32px -16px rgb(0 0 0 / 0.28);
}
.pw-card img {
  display: block;
  width: var(--pw-w);
  height: var(--pw-h);
  max-width: none;
  border-radius: 10px;
  object-fit: cover;
}
.pw-card.is-top {
  z-index: 3;
}
.pw-card.is-next,
.pw-card.is-rest {
  z-index: 2;
  transform: translate(${PEEK.x}px, ${PEEK.y}px) rotate(${PEEK.r}deg) scale(${PEEK.s});
}
.pw-card.is-rest {
  z-index: 1;
  opacity: 0;
}
@media (prefers-reduced-motion: reduce) {
  .pw-stack {
    transition-duration: 0.01ms;
  }
}
`;

The component. Installs to components/dimaac/postcard-word.tsx.

Install

With the shadcn CLI

npx shadcn@latest add https://ui.dimaac.com/r/postcard-word.json

It adds components/dimaac/postcard-word.tsx and installs what it imports. With the @dimaac namespace in components.json (Docs) it's just npx shadcn@latest add @dimaac/postcard-word.

By hand

# Nothing to install: it only needs React
  1. It needs nothing but React 19.
  2. Copy the component file below into components/dimaac/postcard-word.tsx.
  3. It's styled with Tailwind v4 classes. If that folder sits outside the places Tailwind scans, add it with @source in your CSS.
  4. Import it with import { PostcardWord } from "@/components/dimaac/postcard-word" and give its parent a size: it fills it.

Props

PropTypeDefaultDescription
children (required)ReactNode-The word in the sentence, e.g. "outside".
photos (required)string[]-The photos in the stack (image URLs), in the order they pop up. With one photo it is a single card. They are decoration: screen readers hear only the word.
widthnumber156The width of each photo in px.
rationumber1.5The photo's width divided by its height: 1.5 for landscape, 1 for a square portrait.
tiltnumber-2The stack's tilt, in degrees.
side"top" | "bottom""top"Whether the stack opens above or below the word.
framestring"#fff"The colour of each card's frame.
onOpenChange(open: boolean) => void-Called when the stack opens or closes, e.g. to dim the rest of the sentence.
classNamestring""Extra classes around the word, e.g. its colour. The word inherits them.

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.

Prompt
Add the Postcard Word component (<PostcardWord />) from DiMaac UI to this project.

Docs: https://ui.dimaac.com/components/postcard-word
Source and dependencies (shadcn registry JSON): https://ui.dimaac.com/r/postcard-word.json

Install it with:
npx shadcn@latest add https://ui.dimaac.com/r/postcard-word.json

Then use it like this:
import { PostcardWord } from "@/components/dimaac/postcard-word";
<PostcardWord children={children} photos={photos} />

If the shadcn CLI isn't set up here, fetch the registry JSON above, write files[0].content to components/dimaac/postcard-word.tsx.
It uses Tailwind v4 classes, so make sure Tailwind scans that folder. Give its parent a size, keep light and dark mode working and keep its prefers-reduced-motion fallback.
Full index for agents: https://ui.dimaac.com/llms.txt

Files agents read

llms.txt
Every component and how to install it
postcard-word.md
This page as Markdown: install, props and the full source
postcard-word.json
The shadcn registry item

About

A word in a sentence with a small stack of photos behind it, like postcards in a pocket. Point at the word or tab to it and the stack rises above it. Click and the card peeking out from behind pops like toast: it springs up, swaps in front at the top of its arc and lands on the stack with a little weight, then the next card slides out. Square photos suit a name and wide ones a place. Plain React and the Web Animations API. On touch a tap opens it and the next tap pops a card; with reduced motion the cards just swap.

Installs to
components/dimaac/postcard-word.tsx
Uses
React only
Tags
text, hover, images, stack, postcards

Photo: Contemplative Silhouette against Modern Minimalist Architecture by Viri Gutiérrez on Lummi (Lummi License). Photo: Minimalist Stucco Building by Siren Media on Lummi (Lummi License). Photo: Modern Architectural Design by rena on Lummi (Lummi License). Photo: Modern Building Corner by Mikiwa on Lummi (Lummi License). Photo: Minimalist Architectural Design by Mariate on Lummi (Lummi License). Photo: Solitary Tree in Desert by alexaperios on Lummi (Lummi License). Photo: Desert Dunes and Mountain Range by Pablo Stanley on Lummi (Lummi License). Photo: Serene Ocean Aerial View by Mikiwa on Lummi (Lummi License). Photo: Alpine Dawn Serenity by Viri Gutiérrez on Lummi (Lummi License). Photo: Dramatic Coastline Aerial View by Cayetano Gros on Lummi (Lummi License). Photo: Lush Green Hills by SHIHO on Lummi (Lummi License).