dxbh-uiGitHub

Snap Rail

A horizontal rail of any content. Drag it, flick it, wheel it or use the arrow keys; it settles on the nearest slide with a spring that keeps your release velocity, and fades out where slides run under the edge.

Preview

Install

npx shadcn@latest add @dxbh-ui/snap-rail

Add the @dxbh-ui registry to components.json once:

{
  "registries": {
    "@dxbh-ui": "https://ui.dxbh.dev/r/{name}.json"
  }
}

Usage

demo.tsx
"use client";

import { SnapRail } from "@/components/ui/snap-rail/snap-rail";

const cards = [
  { title: "Field notes", kind: "Collection", count: 24, hue: 25 },
  { title: "Quiet rooms", kind: "Playlist", count: 12, hue: 200 },
  { title: "Late trains", kind: "Album", count: 9, hue: 280 },
  { title: "Small tools", kind: "Collection", count: 31, hue: 145 },
  { title: "Long walks", kind: "Route", count: 7, hue: 60 },
  { title: "Paper maps", kind: "Collection", count: 18, hue: 340 },
  { title: "Slow mornings", kind: "Playlist", count: 15, hue: 175 },
  { title: "Open studio", kind: "Event", count: 3, hue: 240 },
];

export default function SnapRailDemo() {
  return (
    <div className="w-full max-w-2xl">
      <SnapRail label="Featured">
        {cards.map((c) => (
          <a
            key={c.title}
            href="#"
            onClick={(e) => e.preventDefault()}
            className="flex h-44 w-40 flex-col justify-between rounded-xl border bg-card p-4 text-card-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/50 sm:w-48"
          >
            <span
              aria-hidden="true"
              className="size-10 rounded-lg"
              style={{ background: `oklch(0.75 0.08 ${c.hue})` }}
            />
            <span>
              <span className="block text-xs text-muted-foreground">{c.kind}</span>
              <span className="mt-0.5 block font-medium">{c.title}</span>
              <span className="mt-1 block text-xs text-muted-foreground tabular-nums">{c.count} items</span>
            </span>
          </a>
        ))}
      </SnapRail>
    </div>
  );
}

Props

PropTypeDefault
children*

One slide per child.

ReactNode—
label*

Accessible name for the rail.

string—
gutter

Inset before the first and after the last slide; slides snap to it.

number24
gap

Space between slides, in px.

number12
fade

Width of the edge fade, in px.

number32
paged

Move at most one snap point per flick.

booleanfalse
controls

Show previous / next buttons and a position counter.

booleantrue
onIndexChange

Fires when the rail settles on a new snap point.

(index: number) => void—
trackClassName

Class names for the moving flex row.

string—

Polish

  • Book and manga domain removed: slides are a children slot, one slide per child.
  • Physics come from @dxbh-ui/use-snap-track: 1:1 tracking after a 10px hysteresis, grab-to-stop mid-flight, release velocity handed to the spring, momentum projection to pick the snap, rubber-banding past both ends.
  • A flick settles with damping 0.8; a slow release settles critically damped.
  • Multi-touch guard: a second finger is ignored while one is dragging, and a drag never fires a click on the slide under the finger.
  • Mostly vertical drags are handed back to the page (touch-action: pan-y), so the rail never traps scrolling.
  • Snap points are deduplicated at the end of the track, so Next disables exactly when the last slide is in view.
  • Scroll-edge mask instead of hard edges, written to the element only when an end is reached, never per frame through React.
  • Arrow keys, Home and End move the rail when it has focus; tabbing into an off-screen slide brings it into view. Keys retarget the same interruptible spring, so held keys never queue animations.
  • Prev and next buttons press to 0.97 and announce the position in a polite live region.
  • Reduced motion: every settle is instant, there is no spring.

Source

snap-rail.tsx
"use client";

import {
  Children,
  useCallback,
  useEffect,
  useRef,
  useState,
  type FocusEvent,
  type HTMLAttributes,
  type KeyboardEvent,
  type ReactNode,
} from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { useSnapTrack } from "@/hooks/use-snap-track";
import { cn } from "@/lib/utils";

export type SnapRailProps = Omit<HTMLAttributes<HTMLElement>, "children" | "onChange"> & {
  /** One slide per child. Any content works: cards, links, buttons. */
  children: ReactNode;
  /** Accessible name for the rail, e.g. "Featured collections". */
  label: string;
  /** Space before the first and after the last slide, in px. Slides snap to this inset. */
  gutter?: number;
  /** Space between slides, in px. */
  gap?: number;
  /** Width of the edge fade where slides run under the viewport edge, in px. */
  fade?: number;
  /** Move at most one snap point per flick, like a paging scroll view. */
  paged?: boolean;
  /** Show previous / next buttons under the rail. */
  controls?: boolean;
  /** Fires when the rail settles on a new snap point. */
  onIndexChange?: (index: number) => void;
  /** Class names for the moving track (the flex row of slides). */
  trackClassName?: string;
};

// Snap points are the offsets that line each slide up with the gutter,
// clamped so the last slides never pull the end of the track off the edge.
// Clamping makes the final few slides share one point, so duplicates collapse.
function measureSnaps(viewport: HTMLElement | null, track: HTMLElement | null, slides: (HTMLElement | null)[], gutter: number) {
  const vw = viewport?.clientWidth ?? 0;
  const tw = track?.scrollWidth ?? 0;
  const min = Math.min(0, vw - tw);
  const points: number[] = [];
  for (const el of slides) {
    if (!el) continue;
    const x = Math.round(Math.max(min, Math.min(0, -(el.offsetLeft - gutter))));
    if (points.length === 0 || points[points.length - 1] !== x) points.push(x);
  }
  return points.length ? points : [0];
}

const maskFor = (fade: number, start: boolean, end: boolean) =>
  `linear-gradient(to right, ${start ? "#000" : "transparent"}, #000 ${fade}px, #000 calc(100% - ${fade}px), ${end ? "#000" : "transparent"})`;

const arrow =
  "inline-flex size-9 cursor-pointer items-center justify-center rounded-full border bg-background text-foreground outline-none " +
  "transition-transform duration-(--duration-press,120ms) ease-out active:scale-[0.97] " +
  "hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-40 [&>svg]:size-4";

/**
 * A horizontal rail of slides you can drag, flick, wheel, arrow-key or button
 * through. Built on useSnapTrack: 1:1 tracking, velocity handoff, projection,
 * rubber-banding, one pointer at a time, and instant settles under reduced motion.
 */
export function SnapRail({
  children,
  label,
  gutter = 24,
  gap = 12,
  fade = 32,
  paged = false,
  controls = true,
  onIndexChange,
  className,
  trackClassName,
  ...props
}: SnapRailProps) {
  const slides = useRef<(HTMLDivElement | null)[]>([]);
  const items = Children.toArray(children);
  const [index, setIndex] = useState(0);
  const [count, setCount] = useState(1);
  const edges = useRef({ start: true, end: false });
  const maskRef = useRef<HTMLDivElement>(null);
  const onIndexChangeRef = useRef(onIndexChange);
  useEffect(() => {
    onIndexChangeRef.current = onIndexChange;
  });

  const snaps = () => measureSnaps(viewportRef.current, trackRef.current, slides.current, gutter);

  // The mask only changes at the ends, so it is written straight to the
  // element when an edge flips, never through React on every frame.
  const paintEdges = (x: number, force = false) => {
    const mask = maskRef.current;
    if (!mask) return;
    const points = snaps();
    const start = x >= Math.max(...points) - 0.5;
    const end = x <= Math.min(...points) + 0.5;
    if (!force && start === edges.current.start && end === edges.current.end) return;
    edges.current = { start, end };
    const image = maskFor(fade, start, end);
    mask.style.maskImage = image;
    mask.style.webkitMaskImage = image;
  };

  const { viewportRef, trackRef, goTo, getIndex, bind } = useSnapTrack({
    snaps,
    paged,
    onMove: (x) => paintEdges(x),
    onIndex: (i) => {
      setIndex(i);
      onIndexChangeRef.current?.(i);
    },
  });

  // Count snap points (not slides) so the buttons disable at the real ends.
  useEffect(() => {
    const viewport = viewportRef.current;
    const measure = () => {
      const points = snaps();
      setCount(points.length);
      paintEdges(points[Math.min(getIndex(), points.length - 1)] ?? 0, true);
    };
    measure();
    if (typeof ResizeObserver === "undefined" || !viewport) return;
    const ro = new ResizeObserver(measure);
    ro.observe(viewport);
    if (trackRef.current) ro.observe(trackRef.current);
    return () => ro.disconnect();
    // snaps reads refs only; re-measure when the slides or spacing change.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [items.length, gutter, gap, fade]);

  const step = useCallback(
    (delta: number) => {
      const next = Math.max(0, Math.min(count - 1, getIndex() + delta));
      if (next !== getIndex()) goTo(next);
    },
    [count, getIndex, goTo],
  );

  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
    // Only when the rail itself has focus; arrows inside a slide's own
    // control (a text field, a slider) belong to that control.
    if (e.target !== e.currentTarget) return;
    if (e.key === "ArrowRight") step(1);
    else if (e.key === "ArrowLeft") step(-1);
    else if (e.key === "Home") goTo(0);
    else if (e.key === "End") goTo(count - 1);
    else return;
    e.preventDefault();
  };

  // Tabbing into an off-screen slide brings it into view.
  const onFocus = (e: FocusEvent<HTMLDivElement>) => {
    const viewport = viewportRef.current;
    if (!viewport || e.target === e.currentTarget) return;
    const slide = slides.current.findIndex((el) => el?.contains(e.target as Node));
    const el = slides.current[slide];
    if (!el) return;
    const points = snaps();
    const current = points[getIndex()] ?? 0;
    const left = el.offsetLeft + current;
    const right = left + el.offsetWidth;
    if (left >= 0 && right <= viewport.clientWidth) return;
    const want = -(el.offsetLeft - gutter);
    const nearest = points.reduce((best, p, i) => (Math.abs(p - want) < Math.abs(points[best] - want) ? i : best), 0);
    goTo(nearest);
  };

  const atStart = index <= 0;
  const atEnd = index >= count - 1;

  return (
    <section aria-roledescription="carousel" aria-label={label} className={cn("relative w-full min-w-0", className)} {...props}>
      {/* The ring lives outside the mask so the faded edges never eat it. */}
      <div className="rounded-lg has-[[data-rail-viewport]:focus-visible]:ring-2 has-[[data-rail-viewport]:focus-visible]:ring-ring/50">
        <div
          ref={maskRef}
          style={{ maskImage: maskFor(fade, true, false), WebkitMaskImage: maskFor(fade, true, false) }}
        >
          <div
            ref={viewportRef}
            {...bind}
            tabIndex={0}
            data-rail-viewport=""
            role="group"
            aria-label={`${label}, use arrow keys to move`}
            onKeyDown={onKeyDown}
            onFocus={onFocus}
            className="relative cursor-grab touch-pan-y overflow-x-clip outline-none select-none active:cursor-grabbing"
          >
            <div
              ref={trackRef}
              className={cn("flex w-max items-stretch py-2 will-change-transform", trackClassName)}
              style={{ paddingInline: gutter, gap }}
            >
              {items.map((child, i) => (
                <div
                  key={(child as { key?: string | null }).key ?? i}
                  ref={(el) => {
                    slides.current[i] = el;
                  }}
                  role="group"
                  aria-roledescription="slide"
                  aria-label={`${i + 1} of ${items.length}`}
                  // Images inside slides would otherwise start a native drag.
                  onDragStart={(e) => e.preventDefault()}
                  className="shrink-0"
                >
                  {child}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {controls && count > 1 ? (
        <div className="mt-3 flex items-center justify-end gap-2" style={{ paddingInline: gutter }}>
          <span className="mr-auto text-xs text-muted-foreground tabular-nums" aria-hidden="true">
            {index + 1} / {count}
          </span>
          <button type="button" className={arrow} onClick={() => step(-1)} disabled={atStart} aria-label="Previous">
            <ChevronLeft />
          </button>
          <button type="button" className={arrow} onClick={() => step(1)} disabled={atEnd} aria-label="Next">
            <ChevronRight />
          </button>
        </div>
      ) : null}
      <span role="status" aria-live="polite" className="sr-only">
        {count > 1 ? `Position ${index + 1} of ${count}` : ""}
      </span>
    </section>
  );
}

Extracted from Kanshelf/web/src/components/home/shelf-rail.tsx at e889ab6.