{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"postcard-word","type":"registry:component","title":"Postcard Word","description":"A word in a sentence that opens a stack of photos you flip through like postcards.","author":"DiMaac (HankTheTank) <https://dimaac.com>","dependencies":[],"files":[{"path":"registry/dimaac/postcard-word/postcard-word.tsx","type":"registry:component","target":"components/dimaac/postcard-word.tsx","content":"\"use client\";\n\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type FocusEvent, type PointerEvent, type ReactNode } from \"react\";\n\n// 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\n// above it; click it and the card peeking out behind pops like toast: it dips for a split second, springs up from\n// behind the front card, slows under gravity until it is clear, swaps in front at the top of its arc, drops back onto\n// the stack and lands with a little weight. Then the next card slides out from behind. On touch, a tap opens the stack\n// and the next tap pops a card.\n\nexport type PostcardWordProps = {\n  /** The word in the sentence, e.g. \"outside\". */\n  children: ReactNode;\n  /** The photos in the stack (image URLs), in the order they pop up. With one photo it is a single card. They are\n   *  decoration: screen readers hear only the word. */\n  photos: string[];\n  /** The width of each photo in px. */\n  width?: number;\n  /** The photo's width divided by its height: 1.5 for landscape, 1 for a square portrait. */\n  ratio?: number;\n  /** The stack's tilt, in degrees. */\n  tilt?: number;\n  /** Whether the stack opens above or below the word. */\n  side?: \"top\" | \"bottom\";\n  /** The colour of each card's frame. */\n  frame?: string;\n  /** Called when the stack opens or closes, e.g. to dim the rest of the sentence. */\n  onOpenChange?: (open: boolean) => void;\n  /** Extra classes around the word, e.g. its colour. The word inherits them. */\n  className?: string;\n};\n\nconst PAD = 5; // the white frame around each photo\nconst PEEK = { x: 10, y: -9, r: 6, s: 0.95 }; // the card waiting behind (keep in sync with .pw-card.is-next)\nconst TUCK = { x: -2, y: 2, r: 0, s: 0.96 }; // fully hidden behind the front card\nconst LOAD = 0.06; // seconds of the small dip before it springs out\nconst LOAD_DIP = 2;\nconst RISE = 0.22; // seconds from launch to the top of the arc\nconst SETTLE = 0.3; // seconds of landing after it touches down\nconst PEEK_OUT = 320; // ms for the next card to slide out from behind\n\ntype Pose = { x: number; y: number; r: number; s: number };\nconst 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)})`;\n\ntype Flight = { frames: Keyframe[]; duration: number; landAt: number };\nconst flights = new Map<number, Flight>();\n\n// Worked out once per card height: a dip, a throw straight up with gravity chosen so it stops just clear of the front\n// card, a free fall onto the stack, then a stiff, well damped spring for the landing so it settles in one soft dip\nfunction flightFor(card: number): Flight {\n  const known = flights.get(card);\n  if (known) return known;\n  const apex = -(card + 10);\n  // The higher the card, the softer and fainter its shadow, like a real one lifting off the table\n  const shadow = (lift: number) => {\n    const fade = Math.max(0, 1 - lift / (card + 6));\n    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)})`;\n  };\n  const start = PEEK.y + LOAD_DIP;\n  const gravity = (2 * (start - apex)) / (RISE * RISE);\n  const fall = Math.sqrt((2 * -apex) / gravity);\n  const top = LOAD + RISE;\n  const landAt = top + fall;\n  const duration = landAt + SETTLE;\n  const stiffness = (2 * Math.PI * 3.4) ** 2;\n  const damping = 2 * 0.62 * Math.sqrt(stiffness);\n  const landTilt = 0.8;\n  let dip = 0;\n  let dipSpeed = gravity * fall * 0.16; // the stack gives a little under the landing card\n  let tilt = landTilt;\n  let tiltSpeed = (landTilt + 3) / fall; // keep the spin it had in the air\n  let springTime = landAt;\n  const frames: Keyframe[] = [];\n  const count = Math.ceil(duration * 60);\n\n  for (let i = 0; i <= count; i++) {\n    const t = Math.min(duration, i / 60);\n    let x = PEEK.x;\n    let y: number;\n    let r: number;\n    let s: number;\n    let lift: number;\n\n    if (t <= LOAD) {\n      const u = t / LOAD;\n      y = PEEK.y + LOAD_DIP * Math.sin((Math.PI / 2) * u);\n      r = PEEK.r;\n      s = PEEK.s;\n      lift = 0;\n    } else if (t <= top) {\n      const tr = t - LOAD;\n      const u = tr / RISE;\n      const ease = u * (2 - u);\n      y = start - gravity * RISE * tr + 0.5 * gravity * tr * tr;\n      r = PEEK.r + (-3 - PEEK.r) * ease;\n      s = PEEK.s + (1 - PEEK.s) * ease;\n      x = PEEK.x * (1 - (t - LOAD) / (landAt - LOAD));\n      lift = Math.max(0, PEEK.y - y);\n    } else if (t <= landAt) {\n      const u = (t - top) / fall;\n      y = apex + 0.5 * gravity * (t - top) ** 2;\n      r = -3 + (landTilt + 3) * u;\n      s = 1 + 0.015 * Math.sin(Math.PI * u);\n      x = PEEK.x * (1 - (t - LOAD) / (landAt - LOAD));\n      lift = Math.max(0, -y);\n    } else {\n      // Step the landing spring forward in small slices for a stable settle\n      while (springTime < t) {\n        const step = Math.min(1 / 480, t - springTime);\n        dipSpeed += (-stiffness * dip - damping * dipSpeed) * step;\n        dip += dipSpeed * step;\n        tiltSpeed += (-stiffness * tilt - damping * tiltSpeed) * step;\n        tilt += tiltSpeed * step;\n        springTime += step;\n      }\n      x = 0;\n      y = dip;\n      r = tilt;\n      s = 1 - 0.02 * Math.max(0, dip / 6);\n      lift = 0;\n    }\n\n    frames.push({\n      offset: t / duration,\n      transform: i === count ? \"none\" : pose({ x, y, r, s }),\n      boxShadow: shadow(lift),\n      zIndex: t < top ? 2 : 4,\n    });\n  }\n\n  const made = { frames, duration: duration * 1000, landAt: landAt * 1000 };\n  flights.set(card, made);\n  return made;\n}\n\n/** The stack's state and the pop. Exported so a page can drive several words' stacks its own way. */\nexport function usePostcards(count: number, card: number) {\n  const [photo, setPhoto] = useState(0);\n  const current = useRef(0);\n  const cards = useRef<(HTMLElement | null)[]>([]);\n  const running = useRef<Animation[]>([]);\n  const busy = useRef(false);\n  const queued = useRef(false);\n\n  const pop = useCallback(() => {\n    if (count < 2) return;\n    if (busy.current) {\n      queued.current = true;\n      return;\n    }\n    const top = current.current;\n    const next = (top + 1) % count;\n    const after = (top + 2) % count;\n\n    if (window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) {\n      setPhoto(next);\n      return;\n    }\n\n    const front = cards.current[top];\n    const incoming = cards.current[next];\n    const waiting = cards.current[after];\n    if (!front || !incoming || !waiting) return;\n\n    busy.current = true;\n    const { frames, duration, landAt } = flightFor(card);\n    const throwCard = incoming.animate(frames, { duration, easing: \"linear\", fill: \"forwards\" });\n\n    // The front card gives a touch as the one behind springs off\n    const press = front.animate([{ transform: \"none\" }, { transform: \"translateY(1.5px)\", offset: 0.45 }, { transform: \"none\" }], { duration: 170, easing: \"ease-in-out\" });\n\n    // The next card waits tucked right behind the front card, then slides out into the peek spot. With two\n    // postcards that card is the old front one, so it starts from where it already is.\n    const tucked = after === top;\n    const slideOut = waiting.animate(\n      [\n        { transform: tucked ? \"none\" : pose(TUCK), opacity: 1, zIndex: tucked ? 3 : 1 },\n        { transform: pose(PEEK), opacity: 1, zIndex: tucked ? 3 : 1 },\n      ],\n      { delay: landAt - 30, duration: PEEK_OUT, easing: \"cubic-bezier(0.3, 0.7, 0.2, 1)\", fill: \"both\" },\n    );\n    running.current = [throwCard, press, slideOut];\n\n    Promise.all([throwCard.finished, slideOut.finished])\n      .then(() => setPhoto(next))\n      .catch(() => {\n        running.current.forEach((animation) => animation.cancel());\n        running.current = [];\n        busy.current = false;\n        queued.current = false;\n      });\n  }, [count, card]);\n\n  // Once the new order is on the page, drop the finished animations so the resting styles take over seamlessly\n  useLayoutEffect(() => {\n    current.current = photo;\n    running.current.forEach((animation) => animation.cancel());\n    running.current = [];\n    busy.current = false;\n    if (queued.current) {\n      queued.current = false;\n      pop();\n    }\n  }, [photo, pop]);\n\n  // Stop any flight if the word goes away mid-air\n  useEffect(() => {\n    const animations = running;\n    return () => animations.current.forEach((animation) => animation.cancel());\n  }, []);\n\n  const place = (index: number) => {\n    if (index === photo) return \"is-top\";\n    if (index === (photo + 1) % count) return \"is-next\";\n    return \"is-rest\";\n  };\n\n  const setCard = (index: number) => (node: HTMLElement | null) => {\n    cards.current[index] = node;\n  };\n\n  return { photo, place, pop, setCard };\n}\n\nexport function PostcardWord({ children, photos, width = 156, ratio = 1.5, tilt = -2, side = \"top\", frame = \"#fff\", onOpenChange, className = \"\" }: PostcardWordProps) {\n  const list = photos;\n  const height = Math.round(width / ratio);\n  const [open, setOpen] = useState(false);\n  const wrap = useRef<HTMLSpanElement>(null);\n  const postcards = usePostcards(list.length, height + PAD * 2);\n  const sources = list.join(\"\\n\");\n\n  // Warm the other photos so each one pops up without a blank frame\n  useEffect(() => {\n    sources\n      .split(\"\\n\")\n      .slice(1)\n      .forEach((src) => {\n        new Image().src = src;\n      });\n  }, [sources]);\n\n  // Tell the page, so it can dim the rest of the sentence while the stack is up\n  const told = useRef(false);\n  useEffect(() => {\n    if (!told.current && !open) return;\n    told.current = true;\n    onOpenChange?.(open);\n  }, [open, onOpenChange]);\n\n  // On a touch screen a tap opens the stack and a tap anywhere else closes it\n  useEffect(() => {\n    if (!open) return;\n    const close = (event: globalThis.PointerEvent) => {\n      if (!(event.target instanceof Node) || !wrap.current?.contains(event.target)) setOpen(false);\n    };\n    document.addEventListener(\"pointerdown\", close);\n    return () => document.removeEventListener(\"pointerdown\", close);\n  }, [open]);\n\n  const enter = (event: PointerEvent) => {\n    if (event.pointerType !== \"touch\") setOpen(true);\n  };\n  const leave = (event: PointerEvent) => {\n    if (event.pointerType !== \"touch\") setOpen(false);\n  };\n  // Keyboard focus opens the stack; a click or tap is handled by onClick instead\n  const focus = (event: FocusEvent<HTMLButtonElement>) => {\n    if (event.currentTarget.matches(\":focus-visible\")) setOpen(true);\n  };\n\n  return (\n    <span ref={wrap} className={`pw ${className}`} style={{ \"--pw-w\": `${width}px`, \"--pw-h\": `${height}px`, \"--pw-tilt\": `${tilt}deg`, \"--pw-frame\": frame } as CSSProperties}>\n      <style href=\"dimaac-postcard-word\" precedence=\"default\">\n        {css}\n      </style>\n      <button\n        type=\"button\"\n        className={`pw-word ${open ? \"is-active\" : \"\"}`}\n        onPointerEnter={enter}\n        onPointerLeave={leave}\n        onFocus={focus}\n        onBlur={() => setOpen(false)}\n        onKeyDown={(event) => event.key === \"Escape\" && setOpen(false)}\n        onClick={() => {\n          if (open) postcards.pop();\n          setOpen(true);\n        }}\n      >\n        {children}\n      </button>\n      <span aria-hidden=\"true\" className={`pw-stack pw-${side} ${open ? \"is-open\" : \"\"}`}>\n        {list.map((src, index) => (\n          <span key={`${src}-${index}`} ref={postcards.setCard(index)} className={`pw-card ${postcards.place(index)}`}>\n            <img src={src} alt=\"\" draggable={false} />\n          </span>\n        ))}\n      </span>\n    </span>\n  );\n}\n\nconst css = `\n.pw {\n  --pw-spring: cubic-bezier(0.34, 1.56, 0.64, 1);\n  position: relative;\n  display: inline-block;\n}\n.pw-word {\n  position: relative;\n  padding: 0;\n  border: 0;\n  background: none;\n  font: inherit;\n  color: inherit;\n  cursor: pointer;\n  text-decoration: underline dotted;\n  text-decoration-color: color-mix(in srgb, currentColor 32%, transparent);\n  text-underline-offset: 4px;\n  transition: color 0.3s, text-decoration-color 0.2s;\n}\n.pw-word:hover,\n.pw-word.is-active {\n  text-decoration-color: currentColor;\n}\n.pw-stack {\n  position: absolute;\n  left: 50%;\n  z-index: 5;\n  width: calc(var(--pw-w) + ${PAD * 2}px);\n  height: calc(var(--pw-h) + ${PAD * 2}px);\n  opacity: 0;\n  pointer-events: none;\n  transition: opacity 0.2s ease, transform 0.55s var(--pw-spring);\n}\n.pw-top {\n  bottom: calc(100% + 10px);\n  transform: translate(-50%, 8px) scale(0.94) rotate(var(--pw-tilt));\n}\n.pw-bottom {\n  top: calc(100% + 10px);\n  transform: translate(-50%, -8px) scale(0.94) rotate(var(--pw-tilt));\n}\n.pw-stack.is-open {\n  opacity: 1;\n  transform: translate(-50%, 0) scale(1) rotate(var(--pw-tilt));\n}\n.pw-card {\n  position: absolute;\n  inset: 0;\n  padding: ${PAD}px;\n  border-radius: 14px;\n  background: var(--pw-frame);\n  box-shadow: 0 0 0 1px rgb(0 0 0 / 0.07), 0 16px 32px -16px rgb(0 0 0 / 0.28);\n}\n.pw-card img {\n  display: block;\n  width: var(--pw-w);\n  height: var(--pw-h);\n  max-width: none;\n  border-radius: 10px;\n  object-fit: cover;\n}\n.pw-card.is-top {\n  z-index: 3;\n}\n.pw-card.is-next,\n.pw-card.is-rest {\n  z-index: 2;\n  transform: translate(${PEEK.x}px, ${PEEK.y}px) rotate(${PEEK.r}deg) scale(${PEEK.s});\n}\n.pw-card.is-rest {\n  z-index: 1;\n  opacity: 0;\n}\n@media (prefers-reduced-motion: reduce) {\n  .pw-stack {\n    transition-duration: 0.01ms;\n  }\n}\n`;\n"}],"categories":["text","hover","images","stack","postcards"],"docs":"import { PostcardWord } from \"@/components/dimaac/postcard-word\". Give its parent a size: it fills it. Docs, playground and props: https://ui.dimaac.com/components/postcard-word","meta":{"tier":"free","preview":"https://ui.dimaac.com/components/postcard-word","credits":[{"by":"Viri Gutiérrez","url":"https://www.lummi.ai/photo/contemplative-silhouette-against-modern-minimalist-architecture-1-haa","what":"Photo: Contemplative Silhouette against Modern Minimalist Architecture","source":"Lummi","licence":"Lummi License"},{"by":"Siren Media","url":"https://www.lummi.ai/photo/minimalist-stucco-building-gurez","what":"Photo: Minimalist Stucco Building","source":"Lummi","licence":"Lummi License"},{"by":"rena","url":"https://www.lummi.ai/photo/modern-architectural-design-aozka","what":"Photo: Modern Architectural Design","source":"Lummi","licence":"Lummi License"},{"by":"Mikiwa","url":"https://www.lummi.ai/photo/modern-building-corner-dr5dz","what":"Photo: Modern Building Corner","source":"Lummi","licence":"Lummi License"},{"by":"Mariate","url":"https://www.lummi.ai/photo/minimalist-architectural-design-b8bbc","what":"Photo: Minimalist Architectural Design","source":"Lummi","licence":"Lummi License"},{"by":"alexaperios","url":"https://www.lummi.ai/photo/solitary-tree-in-desert-wsyns","what":"Photo: Solitary Tree in Desert","source":"Lummi","licence":"Lummi License"},{"by":"Pablo Stanley","url":"https://www.lummi.ai/photo/desert-dunes-and-mountain-range-bfczd","what":"Photo: Desert Dunes and Mountain Range","source":"Lummi","licence":"Lummi License"},{"by":"Mikiwa","url":"https://www.lummi.ai/photo/serene-ocean-aerial-view-kjab6","what":"Photo: Serene Ocean Aerial View","source":"Lummi","licence":"Lummi License"},{"by":"Viri Gutiérrez","url":"https://www.lummi.ai/photo/an-empty-snowy-mountain-with-pink-sunrise-on-the-hori-270fdea6-887e-4d89-8205-3eab907f3fb0-HgoCN","what":"Photo: Alpine Dawn Serenity","source":"Lummi","licence":"Lummi License"},{"by":"Cayetano Gros","url":"https://www.lummi.ai/photo/dramatic-coastline-aerial-view-jml-7","what":"Photo: Dramatic Coastline Aerial View","source":"Lummi","licence":"Lummi License"},{"by":"SHIHO","url":"https://www.lummi.ai/photo/lush-green-hills-mdvvk","what":"Photo: Lush Green Hills","source":"Lummi","licence":"Lummi License"}]}}