{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tilted-tiles",
  "title": "Tilted Tiles",
  "description": "A wall of image columns on a tilted 3D plane, scrolling in a seamless loop under a soft fade while the pointer steers the tilt. No dependencies.",
  "files": [
    {
      "path": "registry/mewo/ui/tilted-tiles.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { cn } from \"@/lib/utils\"\n\nexport interface TiltedTilesProps extends Omit<React.ComponentProps<\"div\">, \"children\"> {\n  /** Image URLs tiled across the plane, each column in its own fixed shuffle. An empty list shows plain placeholder tiles. */\n  images?: string[]\n  /** Number of scrolling columns. */\n  columns?: number\n  /** Tiles in one column before the loop repeats. */\n  tilesPerColumn?: number\n  /** Width divided by height of a single tile. */\n  tileAspect?: number\n  /** Vertical space between tiles, in pixels. */\n  rowGap?: number\n  /** Horizontal space between columns, in pixels. */\n  columnGap?: number\n  /** Corner radius of each tile, in pixels. */\n  borderRadius?: number\n  /** Perspective depth of the scene, in pixels. */\n  perspective?: number\n  /** Degrees the plane leans back. */\n  rotateX?: number\n  /** Degrees the plane turns sideways. */\n  rotateY?: number\n  /** Degrees the plane spins within its own surface. */\n  rotateZ?: number\n  /** Horizontal shift of the plane, in pixels. */\n  offsetX?: number\n  /** Vertical shift of the plane, in pixels. */\n  offsetY?: number\n  /** Depth shift of the plane, in pixels. */\n  offsetZ?: number\n  /** Plane width as a percentage of the root. */\n  planeWidth?: number\n  /** Plane height as a percentage of the root. */\n  planeHeight?: number\n  /** Head start given to alternating columns, as a percentage of a column's width. */\n  stagger?: number\n  /** Seconds a column takes to travel one full loop. */\n  duration?: number\n  /** Send every other column in the opposite direction. */\n  alternate?: boolean\n  /** Height of the top fade, as a percentage of the root. 0 turns it off. */\n  fadeTop?: number\n  /** Height of the bottom fade, as a percentage of the root. 0 turns it off. */\n  fadeBottom?: number\n  /** Let the pointer steer the plane. */\n  parallax?: boolean\n  /** Most degrees the pointer can add to the tilt. */\n  parallaxStrength?: number\n  /** Hold the scroll while the pointer rests on the plane. */\n  pauseOnHover?: boolean\n  /** Saturation of the tiles, where 1 is untouched. */\n  saturation?: number\n}\n\ntype Settings = {\n  rotateX: number\n  rotateY: number\n  rotateZ: number\n  offsetX: number\n  offsetY: number\n  offsetZ: number\n  duration: number\n  alternate: boolean\n  parallax: boolean\n  parallaxStrength: number\n  pauseOnHover: boolean\n  rowGap: number\n  copies: number\n}\n\ntype TileLayout = {\n  columns: number\n  columnGap: number\n  tilesPerColumn: number\n  tileAspect: number\n  rowGap: number\n  planeWidth: number\n  planeHeight: number\n}\n\n// placeholder cats, each a fixed one from cataas.com, so the wall shows the same pictures every time\nexport const DEFAULT_IMAGES = [\"Hf6aYSyQA6KvwdCC\", \"TurdNaGGOVB83svm\", \"B2n9aaCoiKybcCzZ\", \"7kM2cnX1djCXn0ut\", \"1CF7xZmlX0t8QpgP\", \"azOz9jKqE8UBIlec\", \"B4K5IPrryCO0jM1z\", \"3FFBdyyYOHKQQowl\", \"fp5E3gxmEf1Qxcbc\", \"nzb8sRlq6Zweozwx\"].map((id) => `https://cataas.com/cat/${id}`)\n\n// The fade's measured stops: [share of the fade height, opacity]. The fade eases in slowly, then opens up.\nconst FADE_STOPS: [number, number][] = [\n  [0, 0],\n  [0.153, 0.02],\n  [0.171, 0.035],\n  [0.243, 0.075],\n  [0.35, 0.15],\n  [0.5, 0.3],\n  [1, 1],\n]\n// The tilt follows the pointer through two smoothing stages, in seconds: an overdamped ease with no overshoot.\nconst POINTER_TAU = 0.04\nconst TILT_TAU = 0.217\n// While the scroll is held on hover, the loop sleeps once both stages are this close to the pointer (a fraction of\n// the tilt's full range: far under a hundredth of a degree).\nconst SETTLE = 1e-4\n// Frame time is clamped so a hitch or a return from another tab does not jump the scroll.\nconst MIN_DT = 1 / 240\nconst MAX_DT = 0.05\n// The first frame after the loop starts has no previous frame to measure against.\nconst FIRST_DT = 1 / 60\n// A column's strip holds this many copies of its set until the root has been measured, and never fewer or more than these.\nconst UNMEASURED_COPIES = 3\nconst MIN_COPIES = 2\nconst MAX_COPIES = 60\n\nconst clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value))\nconst pct = (value: number) => `${value.toFixed(3)}%`\n\n/** The root's static fade: a mask gradient with `top` and `bottom` percent fades, or undefined with neither. */\nexport function fadeMask(top: number, bottom: number) {\n  if (top <= 0 && bottom <= 0) return undefined\n  const stops: string[] = []\n  if (top > 0) for (const [at, alpha] of FADE_STOPS) stops.push(`rgb(0 0 0 / ${alpha}) ${pct(at * top)}`)\n  else stops.push(\"rgb(0 0 0 / 1) 0%\")\n  if (bottom > 0) for (const [at, alpha] of [...FADE_STOPS].reverse()) stops.push(`rgb(0 0 0 / ${alpha}) ${pct(100 - at * bottom)}`)\n  else stops.push(\"rgb(0 0 0 / 1) 100%\")\n  return `linear-gradient(to bottom, ${stops.join(\", \")})`\n}\n\n/** Each column's fixed shuffle of `count` images; the first column keeps the given order. */\nexport function columnOrder(count: number, column: number) {\n  const order = Array.from({ length: count }, (_, i) => i)\n  if (column === 0) return order\n  let seed = Math.imul(column + 1, 0x9e3779b1) >>> 0\n  const random = () => {\n    seed = (seed + 0x6d2b79f5) >>> 0\n    let t = seed\n    t = Math.imul(t ^ (t >>> 15), t | 1)\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n  }\n  for (let i = count - 1; i > 0; i--) {\n    const j = Math.floor(random() * (i + 1))\n    const swap = order[i]\n    order[i] = order[j]\n    order[j] = swap\n  }\n  return order\n}\n\n/**\n * Copies of a column's set the strip needs to cover the column for the whole loop: one set scrolls out\n * while the rest fill the column. 5 square tiles at the default size need 3; narrow phone columns about 7.\n */\nexport function tileCopies(width: number, height: number, layout: TileLayout) {\n  let copies = UNMEASURED_COPIES\n  if (width > 0 && height > 0) {\n    const columnWidth = ((layout.planeWidth / 100) * width - (layout.columns - 1) * layout.columnGap) / layout.columns\n    const setHeight = layout.tilesPerColumn * (columnWidth / Math.max(0.05, layout.tileAspect) + layout.rowGap)\n    if (setHeight > 0) copies = 1 + Math.ceil(((layout.planeHeight / 100) * height + layout.rowGap) / setHeight)\n  }\n  return clamp(copies, MIN_COPIES, MAX_COPIES)\n}\n\n/** The plane's pose: centred on the root, tilted, then shifted along its own axes. */\nexport function planeTransform(rotateX: number, rotateY: number, rotateZ: number, offsetX: number, offsetY: number, offsetZ: number) {\n  return `translate(-50%, -50%) rotateX(${rotateX.toFixed(4)}deg) rotateY(${rotateY.toFixed(4)}deg) rotate(${rotateZ}deg) translate3d(${offsetX}px, ${offsetY}px, ${offsetZ}px)`\n}\n\n/** A strip `progress` of the way through one loop. One set is (strip height + one gap) / copies tall, so the loop wraps without a jump. */\nexport function stripTransform(progress: number, copies: number, rowGap: number) {\n  return `translate3d(0, calc(${((-progress * 100) / copies).toFixed(4)}% - ${((progress * rowGap) / copies).toFixed(3)}px), 0)`\n}\n\nexport function TiltedTiles({\n  images = DEFAULT_IMAGES,\n  columns = 16,\n  tilesPerColumn = 5,\n  tileAspect = 1,\n  rowGap = 8,\n  columnGap = 8,\n  borderRadius = 0,\n  perspective = 1600,\n  rotateX = 40,\n  rotateY = 16,\n  rotateZ = -20,\n  offsetX = -40,\n  offsetY = 0,\n  offsetZ = 0,\n  planeWidth = 280,\n  planeHeight = 260,\n  stagger = 20,\n  duration = 25,\n  alternate = true,\n  fadeTop = 22,\n  fadeBottom = 0,\n  parallax = true,\n  parallaxStrength = 8,\n  pauseOnHover = false,\n  saturation = 1,\n  className,\n  style,\n  \"aria-label\": ariaLabel,\n  ...props\n}: TiltedTilesProps) {\n  const planeRef = React.useRef<HTMLDivElement>(null)\n  const stripRefs = React.useRef<(HTMLDivElement | null)[]>([])\n  const [size, setSize] = React.useState({ width: 0, height: 0 })\n\n  const cols = Math.max(1, Math.round(columns))\n  const perColumn = Math.max(1, Math.round(tilesPerColumn))\n  const copies = tileCopies(size.width, size.height, { columns: cols, columnGap, tilesPerColumn: perColumn, tileAspect, rowGap, planeWidth, planeHeight })\n\n  const columnTiles = React.useMemo(\n    () =>\n      Array.from({ length: cols }, (_, column) => {\n        if (!images.length) return Array.from({ length: perColumn }, () => \"\")\n        const order = columnOrder(images.length, column)\n        return Array.from({ length: perColumn }, (_, j) => images[order[j % order.length]])\n      }),\n    [images, cols, perColumn]\n  )\n\n  const settings: Settings = { rotateX, rotateY, rotateZ, offsetX, offsetY, offsetZ, duration, alternate, parallax, parallaxStrength, pauseOnHover, rowGap, copies }\n  const settingsRef = React.useRef(settings)\n  // Wakes the loop after a prop change; set by the loop's effect.\n  const wakeRef = React.useRef(() => {})\n  // Frame state lives outside React: progress through one loop, the pointer, and its two smoothing stages.\n  const motionRef = React.useRef({\n    raf: 0,\n    last: 0,\n    progress: 0,\n    hover: false,\n    visible: true,\n    reduced: false,\n    target: { x: 0, y: 0 },\n    pointer: { x: 0, y: 0 },\n    tilt: { x: 0, y: 0 },\n  })\n\n  // Per-frame writes touch only transforms; the mask and the saturation stay on the root untouched.\n  const draw = React.useCallback(() => {\n    const s = settingsRef.current\n    const m = motionRef.current\n    const plane = planeRef.current\n    if (!plane) return\n    plane.style.transform = planeTransform(s.rotateX - m.tilt.y * s.parallaxStrength, s.rotateY + m.tilt.x * s.parallaxStrength, s.rotateZ, s.offsetX, s.offsetY, s.offsetZ)\n    stripRefs.current.forEach((strip, i) => {\n      if (!strip) return\n      strip.style.transform = stripTransform(s.alternate && i % 2 === 1 ? 1 - m.progress : m.progress, s.copies, s.rowGap)\n    })\n  }, [])\n\n  // The loop, the observers and the listeners are set up once; props reach the loop through settingsRef.\n  React.useEffect(() => {\n    // The root's ref stays the consumer's, so the root is reached through the plane.\n    const root = planeRef.current?.parentElement\n    if (!root) return\n    const m = motionRef.current\n\n    const tick = (now: number) => {\n      const dt = m.last ? clamp((now - m.last) / 1000, MIN_DT, MAX_DT) : FIRST_DT\n      m.last = now\n      const s = settingsRef.current\n      const held = s.pauseOnHover && m.hover\n      if (!held) m.progress = (m.progress + dt / Math.max(0.1, s.duration)) % 1\n      const targetX = s.parallax ? m.target.x : 0\n      const targetY = s.parallax ? m.target.y : 0\n      const pointerEase = 1 - Math.exp(-dt / POINTER_TAU)\n      const tiltEase = 1 - Math.exp(-dt / TILT_TAU)\n      // The tilt chases last frame's smoothed pointer, so it reacts one frame after the pointer moves.\n      m.tilt.x += (m.pointer.x - m.tilt.x) * tiltEase\n      m.tilt.y += (m.pointer.y - m.tilt.y) * tiltEase\n      m.pointer.x += (targetX - m.pointer.x) * pointerEase\n      m.pointer.y += (targetY - m.pointer.y) * pointerEase\n      // Held and settled, nothing moves: snap to the target and sleep until the pointer or a prop changes.\n      const settled = [targetX - m.pointer.x, targetY - m.pointer.y, m.pointer.x - m.tilt.x, m.pointer.y - m.tilt.y].every((d) => Math.abs(d) < SETTLE)\n      if (held && settled) {\n        m.pointer.x = m.tilt.x = targetX\n        m.pointer.y = m.tilt.y = targetY\n        draw()\n        m.raf = 0\n        return\n      }\n      draw()\n      m.raf = requestAnimationFrame(tick)\n    }\n\n    // The loop never runs off screen, in a hidden tab or under reduced motion.\n    const start = () => {\n      if (m.raf || m.reduced || !m.visible || document.hidden) return\n      m.last = 0\n      m.raf = requestAnimationFrame(tick)\n    }\n    const stop = () => {\n      cancelAnimationFrame(m.raf)\n      m.raf = 0\n    }\n\n    // Reduced motion freezes the scroll where it is and lays the tilt back to rest.\n    const motionQuery = window.matchMedia?.(\"(prefers-reduced-motion: reduce)\")\n    const onMotionPreference = () => {\n      m.reduced = motionQuery?.matches ?? false\n      if (m.reduced) {\n        stop()\n        for (const point of [m.target, m.pointer, m.tilt]) point.x = point.y = 0\n        draw()\n      } else start()\n    }\n    motionQuery?.addEventListener(\"change\", onMotionPreference)\n    wakeRef.current = start\n\n    const onVisibility = () => {\n      if (document.hidden) stop()\n      else start()\n    }\n    document.addEventListener(\"visibilitychange\", onVisibility)\n\n    const intersection = new IntersectionObserver((entries) => {\n      m.visible = entries[entries.length - 1].isIntersecting\n      if (m.visible) start()\n      else stop()\n    })\n    intersection.observe(root)\n\n    // The strip's copies are counted from the root's size.\n    const resize = new ResizeObserver(([entry]) => {\n      const { width, height } = entry.contentRect\n      setSize((s) => (Math.abs(s.width - width) < 0.5 && Math.abs(s.height - height) < 0.5 ? s : { width, height }))\n    })\n    resize.observe(root)\n\n    const aim = (event: PointerEvent) => {\n      const rect = root.getBoundingClientRect()\n      if (!rect.width || !rect.height) return\n      m.target.x = clamp(((event.clientX - rect.left) / rect.width) * 2 - 1, -1, 1)\n      m.target.y = clamp(((event.clientY - rect.top) / rect.height) * 2 - 1, -1, 1)\n      // only a steering wall moves with the pointer; a held one without parallax stays asleep\n      if (settingsRef.current.parallax) start()\n    }\n    const enter = (event: PointerEvent) => {\n      m.hover = true\n      aim(event)\n    }\n    const leave = () => {\n      m.hover = false\n      m.target.x = m.target.y = 0\n      start()\n    }\n    // A touch has no pointerleave of its own once the finger lifts.\n    const touchEnd = (event: PointerEvent) => {\n      if (event.pointerType !== \"mouse\") leave()\n    }\n    root.addEventListener(\"pointerenter\", enter, { passive: true })\n    root.addEventListener(\"pointermove\", aim, { passive: true })\n    root.addEventListener(\"pointerleave\", leave, { passive: true })\n    root.addEventListener(\"pointerup\", touchEnd, { passive: true })\n    root.addEventListener(\"pointercancel\", touchEnd, { passive: true })\n\n    onMotionPreference()\n    return () => {\n      stop()\n      wakeRef.current = () => {}\n      motionQuery?.removeEventListener(\"change\", onMotionPreference)\n      document.removeEventListener(\"visibilitychange\", onVisibility)\n      intersection.disconnect()\n      resize.disconnect()\n      root.removeEventListener(\"pointerenter\", enter)\n      root.removeEventListener(\"pointermove\", aim)\n      root.removeEventListener(\"pointerleave\", leave)\n      root.removeEventListener(\"pointerup\", touchEnd)\n      root.removeEventListener(\"pointercancel\", touchEnd)\n    }\n  }, [draw])\n\n  // Props reach the loop here, after render, and the wall is redrawn before the browser paints, so a change\n  // shows at once even while the loop is stopped (off screen or reduced motion).\n  React.useLayoutEffect(() => {\n    settingsRef.current = settings\n    stripRefs.current.length = cols\n    draw()\n    wakeRef.current()\n  })\n\n  const mask = fadeMask(fadeTop, fadeBottom)\n\n  return (\n    <div\n      data-slot=\"tilted-tiles\"\n      role={ariaLabel ? \"img\" : undefined}\n      aria-label={ariaLabel}\n      aria-hidden={ariaLabel ? undefined : true}\n      className={cn(\"relative h-full w-full overflow-hidden\", className)}\n      style={{\n        perspective: `${perspective}px`,\n        maskImage: mask,\n        WebkitMaskImage: mask,\n        filter: saturation !== 1 ? `saturate(${saturation})` : undefined,\n        ...style,\n      }}\n      {...props}\n    >\n      <div\n        ref={planeRef}\n        className=\"absolute top-1/2 left-1/2 grid\"\n        style={{\n          width: `${planeWidth}%`,\n          height: `${planeHeight}%`,\n          gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`,\n          columnGap: `${columnGap}px`,\n          // The resting pose, for the first paint and for scripting off; the frame loop takes over from here.\n          transform: planeTransform(rotateX, rotateY, rotateZ, offsetX, offsetY, offsetZ),\n        }}\n      >\n        {columnTiles.map((set, column) => (\n          <div key={column} data-slot=\"tilted-tiles-column\" className=\"overflow-hidden\" style={{ paddingTop: `${stagger * (2 - (column % 3))}%` }}>\n            <div\n              ref={(el) => {\n                stripRefs.current[column] = el\n              }}\n              data-slot=\"tilted-tiles-strip\"\n              className=\"flex flex-col will-change-transform\"\n              style={{ rowGap: `${rowGap}px` }}\n            >\n              {Array.from({ length: copies }, (_, copy) =>\n                set.map((src, j) => (\n                  <div\n                    key={`${copy}-${j}`}\n                    className=\"w-full shrink-0 bg-muted bg-cover bg-center bg-no-repeat\"\n                    style={{ aspectRatio: tileAspect, borderRadius, backgroundImage: src ? `url(${JSON.stringify(src)})` : undefined }}\n                  />\n                ))\n              )}\n            </div>\n          </div>\n        ))}\n      </div>\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "meta": {
    "added": "2026-10-28"
  },
  "categories": [
    "background"
  ],
  "type": "registry:ui"
}