Momentum Rail

A card rail you flick with the mouse — release velocity snaps to the nearest card, scroll position drives cover-flow depth and image parallax with CSS scroll-driven animations.

Momentum Rail

A card rail you flick with the mouse — release velocity snaps to the nearest card, scroll position drives cover-flow depth and image parallax with CSS scroll-driven animations.

The rail displays cards in a horizontal carousel that responds to mouse drag with physics-based momentum. Drag and release to flick through cards — the velocity projects an end point and a spring snaps to the nearest card. The ends rubber-band when you push past them. As cards scroll past the center, CSS scroll-driven animations tilt them in 3D cover-flow style, shift image layers for parallax depth, and fade details in for the centered card. Arrow buttons and keyboard navigation step through cards. Each card can display custom images or built-in drawn scenes, has a favorite toggle, and links to its destination.

Installation

Install the component with the Craft-UI Blocks CLI — it drops momentum-rail.tsx into your project and wires up its runtime dependencies:

npx mvpblocks add momentum-rail
pnpm dlx mvpblocks add momentum-rail
yarn dlx mvpblocks add momentum-rail
bunx mvpblocks add momentum-rail

File Structure

The CLI saves the component to your project's components/ui folder:

Import the default export from @/components/ui/momentum-rail. The item data type is exported as RailItem, scene names as RailScene, and the favorite toggle callback as ToggleFavorite.

Usage

CarouselCards is a client component that takes an array of items. Each item needs an id, title, location, and price. Drop it into any section:

"use client";

import CarouselCards from "@/components/ui/momentum-rail";

const trips = [
  {
    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,
  },
];

export function TravelRail() {
  return <CarouselCards items={trips} />;
}

Use custom images instead of built-in scenes:

const trips = [
  {
    id: "tokyo",
    title: "Late trains and night markets",
    location: "Tokyo, Japan",
    image: "https://images.unsplash.com/photo-1540959733332-eab4deabeeaf?w=520",
    imageAlt: "Tokyo skyline at night",
    badge: "4 nights",
    dates: "Mar 20 – 24",
    price: 890,
    rating: 4.96,
    reviewCount: 402,
  },
];

<CarouselCards items={trips} />

Customize the title and eyebrow:

<CarouselCards
  items={trips}
  title="Summer Adventures"
  eyebrow="Handpicked destinations"
/>

Track favorite toggles:

const [favorites, setFavorites] = useState(["lisbon", "tokyo"]);

function handleToggleFavorite(id: string, favorite: boolean) {
  setFavorites((prev) =>
    favorite ? [...prev, id] : prev.filter((fav) => fav !== id)
  );
  // Optionally sync to your backend
  fetch("/api/favorites", {
    method: "POST",
    body: JSON.stringify({ id, favorite }),
  });
}

<CarouselCards
  items={trips}
  defaultFavorites={favorites}
  onToggleFavorite={handleToggleFavorite}
/>

Handle card selection when cards don't have href:

function handleSelect(item: RailItem) {
  console.log("Selected:", item.title);
  // Navigate programmatically or open a modal
  router.push(`/trips/${item.id}`);
}

<CarouselCards
  items={trips}
  onSelect={handleSelect}
/>

Use card links directly:

const trips = [
  {
    id: "lisbon",
    title: "Weekend in Lisbon",
    location: "Lisbon, Portugal",
    scene: "city",
    price: 340,
    href: "/trips/lisbon",
  },
];

<CarouselCards items={trips} />

Theming

The rail uses zinc tones with semantic status colors. The eyebrow is text-zinc-500 (dark:text-zinc-400) and the title is text-zinc-900 (dark:text-zinc-100).

Cards have rounded-2xl corners with aspect-[4/5] ratio. Card backgrounds are bg-zinc-200 (dark:bg-zinc-800) when using built-in scenes. Images stretch to fill with object-cover.

Badge text appears in bg-white text-zinc-900 (dark:bg-zinc-950 dark:text-zinc-100) with a subtle shadow.

The favorite heart button is bg-white text-zinc-900 (dark:bg-zinc-950 dark:text-zinc-100) with a ring-1 ring-black/5 (dark:ring-white/10). When saved, the heart fills with fill-rose-500 stroke-rose-500.

Card titles are text-zinc-900 (dark:text-zinc-100), locations are text-zinc-500 (dark:text-zinc-400), and details fade in with the centered card.

Arrow buttons have border-zinc-200 bg-white text-zinc-900 (dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-100). At the rail's ends they dim to opacity-40.

Built-in scenes use a palette of zinc layers:

  • 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/Water: fill-zinc-200 (dark:fill-zinc-700)

Each scene (city, mountains, dunes, lake, islands, skyline, terraces, coast) is composed of 4 parallax layers with varying depth.

Animations

  • Drag and flick: The rail follows the pointer one-to-one during drag. On release, velocity is sampled from the last 100ms of movement and projected ahead by DECELERATION^t per millisecond (0.997 per ms, matching UIScrollView). The target is the nearest card to the projected position.
  • Spring snap: After release, a critically damped spring (stiffness 170, damping 26 ≈ 2√170) carries the rail to the target card over ~420ms, settling with no bounce.
  • Rubber band: Dragging past the first or last card encounters resistance. The overshoot distance is damped by rubber(overshoot, size) = sign(overshoot) × (1 - 1 / (abs(overshoot) × 0.55 / size + 1)) × size, creating a smooth asymptotic resistance that never fully stops but requires exponentially more force.
  • Cover-flow tilt: Each card defines a view timeline on the inline axis (0% entering right, 50% centered, 100% leaving left). The card rotates in 3D from -14deg through 0deg to 14deg and translates toward the viewer by -180px at the edges, reaching 0px at center. This runs off the main thread via CSS scroll-driven animations.
  • Parallax layers: Images and scene layers animate translateX from -depth% to +depth% along the same timeline, with deeper layers moving more. Each scene layer has its own depth value (e.g., sun at 2%, far mountains at 4%, mid ground at 7%, foreground at 11%).
  • Details fade: Rating, dates, and price fade from opacity: 0 at 0%/32% to opacity: 1 at 45%/55%, then back to opacity: 0 at 68%/100%, revealing only for the centered card.
  • Heart fill: The favorite heart fills from bottom to top via clip-path: inset(100% 0 0 0) to inset(0 0 0 0) over 300ms ease-out when toggled on.
  • Arrow dim: Arrow buttons fade to 40% opacity via aria-disabled at the rail's ends.
  • Native fallback: Browsers without @supports (animation-timeline: view()) get flat cards with all details visible and no 3D tilt or parallax.
  • Reduced motion: With prefers-reduced-motion: reduce, the spring snaps instantly to the target, tilt and parallax are disabled, and only the details fade remains (driven by scroll position, not time).

How it works

The component combines JavaScript physics for flick momentum and CSS scroll-driven animations for visual depth. The JavaScript owns the scroll position during drag and spring, while native scrolling takes over at rest.

Momentum Physics

The useMomentumRail hook manages a state machine with four modes: idle (native scroll snap), pressing (pointer down, waiting for drag threshold), dragging (actively moving), and spring (animating to a card).

On pointerdown, if the rail is mid-spring (mode === "spring"), the press "catches" it by capturing its current virtual position (including any rubber-band overshoot). Otherwise, it starts from the native scrollLeft. Movement over 4px enters dragging mode, which:

  1. Captures the pointer to receive all pointermove events
  2. Disables native scroll snap (scroll-snap-type: none via data-free="true")
  3. Writes a virtual position by setting scrollLeft for the in-range part and applying translateX to the track for overshoot (the rubber band)
  4. Samples the last 100ms of (timestamp, clientX) pairs

On release, velocity is computed as (last.x - first.x) / (last.t - first.t) in px/ms. The position is projected by velocity × DECELERATION / (1 - DECELERATION), which sums the infinite geometric series of deceleration. The nearest snap point to the projected position becomes the spring's target.

The spring integrates force = -STIFFNESS × (pos - target) - DAMPING × vel with semi-implicit Euler substeps (4 per frame) for stability. When |pos - target| < 0.5 and |vel| < 8, the spring settles exactly on the target and hands back to native snap.

If a drag ends over a stretched link or button, a clickCapture listener with preventDefault suppresses the click to avoid accidental navigation.

Scroll-Driven Animations

Each card has a view-timeline: --kokonutui-rail inline, which defines a timeline scoped to that card's visibility along the horizontal axis. Three animations bind to this timeline:

  1. kokonutui-rail-tilt: Animates the card's 3D transform from perspective(900px) translateZ(-180px) rotateY(-14deg) at 0% (entering right), through translateZ(0) rotateY(0deg) at 50% (centered), to the mirrored exit state at 100%.
  2. kokonutui-rail-parallax: Each image or scene layer translates from calc(var(--rail-depth) × -1) to var(--rail-depth), where --rail-depth is the layer's depth percentage (e.g., 8% for images, 2% to 11% for scene layers).
  3. kokonutui-rail-details: The rating, dates, and price fade in from 32% to 45%, hold full opacity 45%–55%, then fade out 55%–68%.

These animations run on the compositor thread, so scrolling and momentum remain smooth even during heavy main-thread work. The component injects keyframes via a <style> tag with href="kokonutui-carousel-cards" and precedence="default", which React deduplicates across multiple rails on the page.

Snap Points

Snap points are calculated from each card's center position. For a card at track.offsetLeft + card.offsetLeft + card.offsetWidth / 2, the snap point is that center minus half the scroller's width, clamped to [0, maxScroll]. This centers cards in the viewport.

The spring always targets a snap point, and native scroll snap (when data-free="false") lands on the same points, so the transition between JS-driven and native scrolling is seamless.

Built-in Scenes

Eight scenes are pre-drawn as flat SVG layers: city, mountains, dunes, lake, islands, skyline, terraces, coast. Each scene has 4 layers with depth values (sun, far, mid, near), rendered as zinc-toned shapes. When an item has no image prop, its scene (defaulting to "mountains") renders instead.

Keyboard Navigation

The rail is focusable (tabIndex={0}) and listens for ArrowLeft, ArrowRight, Home, and End. Arrow keys step one card forward or back by calling goTo(currentIndex() ± 1), which springs to the new target. Home jumps to the first card, End to the last. The scroller receives focus, not individual cards, so tabbing into the rail puts you in navigation mode.

Favorites

Favorites are tracked in a Set<string> of item ids. The defaultFavorites prop seeds the set on first render. Toggling a heart calls onToggleFavorite(id, newState) and updates the local set. The parent can sync the state to localStorage or a backend.

Native Takeover

Mouse wheel and touch gestures call onNativeInput, which cancels any running spring and lets native inertia take over. This respects user intent: if you start a wheel scroll mid-spring, the spring stops and the wheel controls the rail.

Props

Prop

Type

RailItem Object

Prop

Type

Accessibility

  • The rail is a role="carousel" landmark with aria-label matching the title.
  • The scroller is focusable (tabIndex={0}) with aria-label instructing "use arrow keys to move". Focus moves to the scroller, not individual cards.
  • Arrow keys navigate: ArrowLeft/ArrowRight step one card, Home jumps to the first card, End to the last.
  • A live region announces the current position as "Card 03 / 08" when it changes.
  • Arrow buttons use aria-disabled="true" (not disabled) at the ends, so focus stays on the button rather than jumping away.
  • Card links/buttons are stretched over the entire card with an ::after pseudo-element, making the full card clickable. The favorite button sits above this layer via higher z-index.
  • Each card has a visible focus ring on the stretched link/button, not the card wrapper, so keyboard users see where they are.
  • Images have alt text (defaulting to empty when the title already names the card), and draggable={false} prevents accidental drag-to-download.
  • Built-in scenes are aria-hidden decorative SVGs.

Registry Bundle

Install the exact registry entry shown on the right when you want the component file and its declared runtime dependencies together. Dependencies: lucide-react (for ChevronLeft, ChevronRight, and Star icons).

Contact

If you find any bug or issue, feel free to raise an issue.

Last updated on