# Momentum Rail
> A card rail you flick with momentum, snapping on a spring, with scroll-driven cover-flow depth and parallax.

Source: https://kokonutui.com/docs/cards/carousel-cards

## Installation

```bash
npx shadcn@latest add @kokonutui/carousel-cards
```

## Props

| Prop                       | Type                | Default           | Description                                                                                   |
|----------------------------|---------------------|-------------------|-----------------------------------------------------------------------------------------------|
| `items?`                  | `RailItem[]`        | `built-in`        |                                                                                               |
| `title?`                  | `string`            | `"Weekend escapes"` |                                                                                               |
| `eyebrow?`                | `string`            | `"Picked for this autumn"` |                                                                                               |
| `defaultFavorites?`       | `string[]`          | `[]`             | Ids saved on first render.                                                                    |
| `onToggleFavorite?`       | `ToggleFavorite`     |                   | Called when a card's heart is toggled, with the item id and new state.                      |
| `onSelect?`               | `(item: RailItem) => void` |                   | Called when a card without an `href` is clicked or activated.                               |
| `className?`              | `string`            |                   | Extra classes for the root element.                                                           |

### RailItem

| Field         | Type       | Description                                                 |
|---------------|------------|-------------------------------------------------------------|
| `id`          | `string`   |                                                             |
| `title`       | `string`   |                                                             |
| `location`    | `string`   |                                                             |
| `image?`      | `string`   | Photo URL, rendered with a plain <img>. Falls back to `scene`. |
| `imageAlt?`   | `string`   | Alt text for `image`. Empty by default: the title already names it. |
| `scene?`      | `RailScene`| Built-in drawn artwork, used when there is no `image`.      |
| `badge?`      | `string`   |                                                             |
| `dates?`      | `string`   |                                                             |
| `price`       | `number`   |                                                             |
| `currency?`   | `string`   |                                                             |
| `priceLabel?` | `string`   |                                                             |
| `rating?`     | `number`   |                                                             |
| `reviewCount?`| `number`   |                                                             |
| `href?`       | `string`   |                                                             |

### ToggleFavorite

```ts
type ToggleFavorite = (id: string, favorite: boolean) => void;
```

### RailScene

```ts
type RailScene = | "city" | "mountains" | "dunes" | "lake" | "islands" | "skyline" | "terraces" | "coast";
```

## Source

```tsx
"use client";

/**
 * @author: @dorianbaffier
 * @description: Momentum Rail. A card rail you can flick with the mouse: the
 * release velocity projects an end point, a spring snaps to the nearest card
 * and the ends rubber-band. Scroll position drives a cover-flow depth, image
 * parallax and the centered card's details with CSS scroll-driven animations.
 * @version: 2.0.0
 * @date: 2026-10-14
 * @license: MIT
 * @website: https://kokonutui.com
 * @github: https://github.com/kokonut-labs/kokonutui
 */

import { ChevronLeft, ChevronRight, Star } from "lucide-react";
import {  type CSSProperties, type ReactNode, type RefObject, useCallback, useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";

export type RailScene =
  | "city"
  | "mountains"
  | "dunes"
  | "lake"
  | "islands"
  | "skyline"
  | "terraces"
  | "coast";

export interface RailItem {
  id: string;
  title: string;
  location: string;
  /** Photo URL, rendered with a plain <img>. Falls back to `scene`. */
  image?: string;
  /** Alt text for `image`. Empty by default: the title already names it. */
  imageAlt?: string;
  /** Built-in drawn artwork, used when there is no `image`. */
  scene?: RailScene;
  badge?: string;
  dates?: string;
  price: number;
  currency?: string;
  priceLabel?: string;
  rating?: number;
  reviewCount?: number;
  href?: string;
}

export type ToggleFavorite = (id: string, favorite: boolean) => void;

export interface CarouselCardsProps {
  items?: RailItem[];
  title?: string;
  eyebrow?: string;
  /** Ids saved on first render. */
  defaultFavorites?: string[];
  /** Called when a card's heart is toggled, with the item id and new state. */
  onToggleFavorite?: ToggleFavorite;
  /** Called when a card without an `href` is clicked or activated. */
  onSelect?: (item: RailItem) => void;
  className?: string;
}

const DEFAULT_ITEMS: RailItem[] = [
  {
    id: "lisbon",
    title: "Weekend in Lisbon",
    location: "Lisbon, Portugal",
    scene: "city",
    badge: "2 nights",
    dates: "Oct 24 – 26",
    price: 340,
    rating: 4.92,
    reviewCount: 318,
  },
  {
    id: "dolomites",
    title: "Slow days in the Dolomites",
    location: "Val Gardena, Italy",
    scene: "mountains",
    badge: "4 nights",
    dates: "Nov 3 – 7",
    price: 610,
    rating: 4.97,
    reviewCount: 142,
  },
  {
    id: "dunes",
    title: "Two nights in the dunes",
    location: "Merzouga, Morocco",
    scene: "dunes",
    badge: "2 nights",
    dates: "Nov 14 – 16",
    price: 280,
    rating: 4.88,
    reviewCount: 96,
  },
  {
    id: "lapland",
    title: "Lake cabin under the aurora",
    location: "Inari, Finland",
    scene: "lake",
    badge: "3 nights",
    dates: "Dec 5 – 8",
    price: 520,
    rating: 4.95,
    reviewCount: 210,
  },
  {
    id: "naxos",
    title: "Island hopping by ferry",
    location: "Naxos, Greece",
    scene: "islands",
    badge: "5 nights",
    dates: "May 9 – 14",
    price: 740,
    rating: 4.9,
    reviewCount: 187,
  },
  {
    id: "tokyo",
    title: "Late trains and night markets",
    location: "Tokyo, Japan",
    scene: "skyline",
    badge: "4 nights",
    dates: "Mar 20 – 24",
    price: 890,
    rating: 4.96,
    reviewCount: 402,
  },
  {
    id: "ubud",
    title: "Rice terraces at dawn",
    location: "Ubud, Indonesia",
    scene: "terraces",
    badge: "3 nights",
    dates: "Jan 12 – 15",
    price: 390,
    rating: 4.91,
    reviewCount: 133,
  },
  {
    id: "coast-road",
    title: "Coast road, windows down",
    location: "Big Sur, United States",
    scene: "coast",
    badge: "3 nights",
    dates: "Apr 2 – 5",
    price: 560,
    rating: 4.89,
    reviewCount: 158,
  },
];

const RAIL_CSS = `
@keyframes kokonutui-rail-tilt {
  0% { transform: perspective(900px) translateZ(-180px) rotateY(-14deg); }
  50% { transform: perspective(900px) translateZ(0) rotateY(0deg); }
  100% { transform: perspective(900px) translateZ(-180px) rotateY(14deg); }
}
@keyframes kokonutui-rail-parallax {
  from { transform: translate3d(calc(var(--rail-depth) * -1), 0, 0); }
  to { transform: translate3d(var(--rail-depth), 0, 0); }
}
@keyframes kokonutui-rail-details {
  0%, 32% { opacity: 0; transform: translate3d(0, 6px, 0); }
  45%, 55% { opacity: 1; transform: translate3d(0, 0, 0); }
  68%, 100% { opacity: 0; transform: translate3d(0, 6px, 0); }
}
@supports (animation-timeline: view()) {
  .kokonutui-rail-card { view-timeline: --kokonutui-rail inline; }
  .kokonutui-rail-details {
    animation: kokonutui-rail-details linear both;
    animation-timeline: --kokonutui-rail;
  }
  @media (prefers-reduced-motion: no-preference) {
    .kokonutui-rail-tilt {
      animation: kokonutui-rail-tilt linear both;
      animation-timeline: --kokonutui-rail;
    }
    .kokonutui-rail-layer {
      animation: kokonutui-rail-parallax linear both;
      animation-timeline: --kokonutui-rail;
    }
  }
}
`;

const TONE = {
  sun: "fill-white dark:fill-zinc-400",
  far: "fill-zinc-300 dark:fill-zinc-800",
  mid: "fill-zinc-400 dark:fill-zinc-900",
  near: "fill-zinc-600 dark:fill-zinc-950",
  sky: "fill-zinc-200 dark:fill-zinc-700",
} as const;

const Scene = ({ scene }: { scene: RailScene }) => (
  <div
    aria-hidden="true"
    className="absolute inset-0 bg-zinc-200 dark:bg-zinc-700"
  >
    {SCENES[scene].map((layer) => (
      <div
        className={LAYER_CLASS}
        key={layer.depth}
        style={{ "--rail-depth": `${layer.depth}%` } as CSSProperties}
      >
        <svg
          aria-hidden="true"
          className="h-full w-full"
          preserveAspectRatio="xMidYMax slice"
          viewBox="0 0 208 200"
        >
          {layer.content}
        </svg>
      </div>
    ))}
  </div>
);

const RailCard = ({ item, saved, onToggleSaved, onSelect }: { item: RailItem; saved: boolean; onToggleSaved: (id: string) => void; onSelect?: (item: RailItem) => void; }) => (
  <li className="kokonutui-rail-card w-(--rail-card) flex-none snap-center">
    <div className="kokonutui-rail-tilt group/rail-card relative">
      <div className="relative aspect-[4/5] overflow-hidden rounded-2xl bg-zinc-200 ring-zinc-900 ring-offset-2 ring-offset-white group-has-[[data-rail-link]:focus-visible]/rail-card:ring-2 dark:bg-zinc-800 dark:ring-zinc-100 dark:ring-offset-zinc-950">
        {item.image ? (
          <div className={cn(LAYER_CLASS, "[--rail-depth:8%]")}>    
            <img
              alt={item.imageAlt ?? ""}
              className="h-full w-full object-cover"
              decoding="async"
              draggable={false}
              height={500}
              loading="lazy"
              src={item.image}
              width={520}
            />
          </div>
        ) : (
          <Scene scene={item.scene ?? "mountains"} />
        )}
        {item.badge && (
          <span className="absolute top-3 left-3 rounded-md bg-white px-1.5 py-0.5 font-medium text-[11px] text-zinc-900 shadow-sm dark:bg-zinc-950 dark:text-zinc-100">
            {item.badge}
          </span>
        )}
        <FavoriteButton label={item.title} onToggle={() => onToggleSaved(item.id)} saved={saved} />
      </div>

<div className="px-0.5 pt-3">
        <h3 className="truncate font-medium text-sm text-zinc-900 tracking-tight dark:text-zinc-100">
          {item.href ? (
            <a
              className={STRETCHED}
              data-rail-link=""
              draggable={false}
              href={item.href}
            >
              {item.title}
            </a>
          ) : (
            <button
              className={cn(STRETCHED, "cursor-pointer text-left")}
              data-rail-link=""
              onClick={() => onSelect?.(item)}
              type="button"
            >
              {item.title}
            </button>
          )}
        </h3>
        <p className="truncate text-xs text-zinc-500 dark:text-zinc-400">
          {item.location}
        </p>
        <CardDetails item={item} />
      </div>
    </div>
  </li>
);

export default function CarouselCards({ items = DEFAULT_ITEMS, title = "Weekend escapes", eyebrow = "Picked for this autumn", defaultFavorites = [], onToggleFavorite, onSelect, className, }: CarouselCardsProps) {
  const scrollerRef = useRef<HTMLElement>(null);
  const trackRef = useRef<HTMLUListElement>(null);
  const [active, setActive] = useState(0);
  const [saved, setSaved] = useState<ReadonlySet<string>>(() => new Set(defaultFavorites));
  const { goTo, currentIndex } = useMomentumRail(scrollerRef, trackRef, setActive);

const toggleSaved = (id: string) => {
    const next = !saved.has(id);
    setSaved((prev) => {
      const copy = new Set(prev);
      if (next) {
        copy.add(id);
      } else {
        copy.delete(id);
      }
      return copy;
    });
    onToggleFavorite?.(id, next);
  };

const step = (delta: number) => goTo(currentIndex() + delta);

return (
    <section
      aria-label={title}
      aria-roledescription="carousel"
      className={cn("@container/rail w-full py-4 @3xl/rail:[--rail-card:16rem] @md/rail:[--rail-card:15rem] [--rail-card:13.5rem]", className)}
    >
      <div className="mb-2 flex items-end justify-between gap-4 px-4">
        <div className="min-w-0">
          <p className="text-xs text-zinc-500 dark:text-zinc-400">{eyebrow}</p>
          <h2 className="truncate font-semibold text-lg text-zinc-900 tracking-tight dark:text-zinc-100">
            {title}
          </h2>
        </div>
        <div className="flex shrink-0 items-center gap-2">
          <span
            aria-live="polite"
            className="mr-1 text-xs text-zinc-500 tabular-nums dark:text-zinc-400"
          >
            <span className="sr-only">Card </span>
            {String(active + 1).padStart(2, "0")}
            <span aria-hidden="true"> / </span>
            <span className="sr-only"> of </span>
            {String(items.length).padStart(2, "0")}
          </span>
          <button
            aria-disabled={active === 0}
            aria-label="Previous"
            className={ARROW_CLASS}
            onClick={() => step(-1)}
            type="button"
          >
            <ChevronLeft aria-hidden="true" className="size-4" />
          </button>
          <button
            aria-disabled={active === items.length - 1}
            aria-label="Next"
            className={ARROW_CLASS}
            onClick={() => step(1)}
            type="button"
          >
            <ChevronRight aria-hidden="true" className="size-4" />
          </button>
        </div>
      </div>

<section
        aria-label={`${title}, use arrow keys to move`}
        className="relative snap-x snap-mandatory overflow-x-auto overscroll-x-contain py-6 outline-none [scrollbar-width:none] focus-visible:ring-2 focus-visible:ring-zinc-900 focus-visible:ring-inset data-[dragging=true]:cursor-grabbing data-[free=true]:snap-none dark:focus-visible:ring-zinc-100 [&::-webkit-scrollbar]:hidden [@media(pointer:fine)]:cursor-grab [@media(pointer:fine)]:select-none"
        ref={scrollerRef}
        tabIndex={0}
      >
        <ul
          className="relative flex w-max gap-4 px-[calc(50cqw-var(--rail-card)/2)]"
          ref={trackRef}
        >
          {items.map((item) => (
            <RailCard
              item={item}
              key={item.id}
              onSelect={onSelect}
              onToggleSaved={toggleSaved}
              saved={saved.has(item.id)}
            />
          ))}
        </ul>
      </section>

<style href="kokonutui-carousel-cards" precedence="default">
        {RAIL_CSS}
      </style>
    </section>
  );
}
```
