{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "marquee",
  "title": "Marquee",
  "description": "Rows that drift sideways forever at a pace the feel sets, held while out of view and when told to, and still under reduced motion: the Testimonials and Logo cloud marquees.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/resize.json",
    "https://kinoui.com/r/scroll.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/lib/marquee.tsx",
      "content": "'use client'\n\nimport { reducesMotion } from '@/registry/lib/reduce-motion'\nimport {\n  FOLLOWS_TRANSITION,\n  roleDuration,\n  withoutTransition,\n} from '@/registry/lib/resize'\nimport {\n  scrollRegionRingClassName,\n  useEdgeFades,\n  useScrollRegion,\n} from '@/registry/lib/scroll'\nimport {\n  Children,\n  type ReactNode,\n  type RefObject,\n  useCallback,\n  useEffect,\n  useId,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * Rows that drift sideways forever, at an even pace the feel sets: the\n * Testimonials marquee's quotes and the Logo cloud's logos. A row is its\n * items, then copies of them, as many as fill it, so the drift never runs\n * out, and one copy before them, so the first item can come clear of the\n * faded start; the copies are hidden from screen readers and can't take focus.\n *\n * A row holds still while it is out of view, and while its caller's `hold`\n * says so (the `hold` lib: the pointer is over the rows, a finger presses\n * them or an item has focus),\n * and an item that takes focus comes clear of the faded ends. Under reduced\n * motion a row stands still and scrolls sideways instead, so every item is\n * still in reach.\n *\n *   const hold = useHold()\n *   <div {...hold.handlers}>\n *     <MarqueeRow label='Customers' running={hold.running} driftVariable='--logo-cloud-drift'>\n *       {logos}\n *     </MarqueeRow>\n *   </div>\n */\n\n/**\n * One row: its items, drifting the way the page reads, or back with\n * `reverse`. `driftVariable` names the CSS variable a buyer sets the pace\n * with, in rem per `layout` duration, such as `--testimonials-drift`.\n */\nfunction MarqueeRow({\n  label,\n  reverse = false,\n  running,\n  driftVariable,\n  trackClassName,\n  children,\n}: {\n  /** Names the row for a screen reader when it stands still and scrolls. */\n  label: string\n  reverse?: boolean\n  running: boolean\n  driftVariable: `--${string}`\n  /** The gap between the items and the room at the row's ends. */\n  trackClassName?: string\n  children: ReactNode\n}) {\n  const labelId = useId()\n  const viewportRef = useRef<HTMLDivElement>(null)\n  const shiftRef = useRef<HTMLDivElement>(null)\n  const trackRef = useRef<HTMLDivElement>(null)\n  const copyRef = useRef<HTMLDivElement>(null)\n  const leadRef = useRef<HTMLDivElement>(null)\n  const fades = useEdgeFades<HTMLDivElement>()\n  const [copies, setCopies] = useState(1)\n  const { control, still } = useDrift(\n    { viewportRef, shiftRef, trackRef, copyRef, leadRef },\n    { reverse, running, driftVariable, setCopies },\n  )\n  // Standing still, it scrolls, so it takes focus as a region a keyboard can scroll.\n  const region = useScrollRegion(viewportRef, {\n    axis: 'x',\n    labelledBy: useCallback(() => labelId, [labelId]),\n  })\n\n  useEffect(() => {\n    control.current?.(running)\n  }, [control, running])\n\n  return (\n    <div className={cn('min-w-0', scrollRegionRingClassName)}>\n      <span id={labelId} hidden>\n        {label}\n      </span>\n      <div\n        ref={(node) => {\n          viewportRef.current = node\n          return fades(node)\n        }}\n        data-slot='marquee-row'\n        {...(still ? region : undefined)}\n        onFocus={(event) => {\n          // Held at once, before React renders, so the item stays where it is brought.\n          control.current?.(false)\n          // Standing still, the row scrolls the item into view itself.\n          if (!still && event.target.matches(':focus-visible')) bringClear(event.target)\n        }}\n        className={cn(\n          // While it drifts it is clipped and fades at both ends. Standing still it\n          // scrolls instead, and an end fades only while there is more past it.\n          'scrollbar-thin overflow-x-clip [--marquee-fade:min(6rem,12%)] [mask-image:linear-gradient(to_right,transparent,black_var(--marquee-fade),black_calc(100%-var(--marquee-fade)),transparent)] focus-visible:outline-hidden motion-reduce:overflow-x-auto motion-reduce:[mask-image:linear-gradient(to_right,transparent,black_var(--scroll-fade-left,0px),black_calc(100%-var(--scroll-fade-right,0px)),transparent)]',\n        )}\n      >\n        {/* Moves an item that takes focus clear of the faded ends, on `layout`. */}\n        <div\n          ref={shiftRef}\n          data-slot='marquee-shift'\n          className='w-max transition-[translate] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:transition-none'\n        >\n          <div\n            ref={trackRef}\n            role='list'\n            className={cn('relative flex w-max', trackClassName)}\n          >\n            <Items>{children}</Items>\n            <div\n              ref={copyRef}\n              data-slot='marquee-copy'\n              aria-hidden\n              inert\n              // The track's gap between its copies too, so every item stands the same distance apart.\n              className='flex gap-[inherit] motion-reduce:hidden'\n            >\n              {Array.from({ length: copies }, (_, copy) => (\n                <Items key={copy}>{children}</Items>\n              ))}\n            </div>\n            {/* A set's length before the items, where the drift places it. */}\n            <div\n              ref={leadRef}\n              data-slot='marquee-copy'\n              aria-hidden\n              inert\n              className='absolute inset-y-0 flex items-[inherit] gap-[inherit] py-[inherit] motion-reduce:hidden'\n            >\n              <Items>{children}</Items>\n            </div>\n          </div>\n        </div>\n      </div>\n    </div>\n  )\n}\n\n/** Each item as an item of the row's list, standing its own size. */\nfunction Items({ children }: { children: ReactNode }) {\n  return Children.map(children, (child) => (\n    <div role='listitem' className='flex shrink-0'>\n      {child}\n    </div>\n  ))\n}\n\n/** Items dealt into `rows` rows in turn, as cards are dealt: the first to the first row, the second to the second. */\nfunction dealRows<Item>(items: readonly Item[], rows: number): Item[][] {\n  const count = Math.min(rows, items.length)\n  return Array.from({ length: count }, (_, row) =>\n    items.filter((_, index) => index % count === row),\n  )\n}\n\n/** How many copies of a row's items fill it, so the drift never shows an empty end: at least one. */\nfunction copiesToFill(rowWidth: number, setWidth: number) {\n  if (!(setWidth > 0)) return 1\n  return Math.max(1, Math.ceil(rowWidth / setWidth))\n}\n\n/** How far a row drifts in one `layout` duration, in rem: about 30px a second in the default feel. */\nconst DRIFT_REM = 1.25\n\n/**\n * A row's drift: a Web Animation that moves the track by one set of its\n * items, linearly and forever, so the copy behind lands where the items\n * began. One set takes as many `layout` durations as it holds drifts, so the\n * feel sets its pace, and it is rebuilt from where it was when the feel, the\n * reduced motion or the row's width changes. It plays while `running`, and\n * holds while the row is out of view; under reduced motion it stands still.\n * Its pace is `layout`'s, so a tool that slows the roles, such as the\n * playground's Speed, slows it too, rebuilt as for a new feel.\n */\nfunction useDrift(\n  {\n    viewportRef,\n    shiftRef,\n    trackRef,\n    copyRef,\n    leadRef,\n  }: Record<\n    'viewportRef' | 'shiftRef' | 'trackRef' | 'copyRef' | 'leadRef',\n    RefObject<HTMLDivElement | null>\n  >,\n  {\n    reverse,\n    running,\n    driftVariable,\n    setCopies,\n  }: {\n    reverse: boolean\n    running: boolean\n    driftVariable: string\n    setCopies: (copies: number) => void\n  },\n) {\n  const control = useRef<((play: boolean) => void) | null>(null)\n  const runningRef = useRef(running)\n  useEffect(() => {\n    runningRef.current = running\n  })\n  const [still, setStill] = useState(false)\n  useEffect(() => {\n    const viewport = viewportRef.current\n    const shift = shiftRef.current\n    const track = trackRef.current\n    const copy = copyRef.current\n    const lead = leadRef.current\n    if (!viewport || !shift || !track || !copy || !lead) return\n    let animation: Animation | null = null\n    // The way the row lays out, read where it stands, so it follows `dir` however it is set.\n    let rtl = false\n    let wanted = runningRef.current\n    let seen = false\n    const apply = () => {\n      if (!animation) return\n      if (wanted && seen) {\n        settleShift(animation, shift, track, rtl)\n        animation.play()\n      } else animation.pause()\n    }\n    const build = () => {\n      const progress = animation ? progressOf(animation) : 0\n      animation?.cancel()\n      animation = null\n      rtl = isRtl(viewport)\n      const reduced = reducesMotion(viewport)\n      setStill(reduced)\n      if (reduced) return\n      const length = setWidth(track, copy, rtl)\n      setCopies(copiesToFill(viewport.clientWidth, length))\n      lead.style.insetInlineStart = `${firstOffset(track, rtl) - length}px`\n      const rem = Number.parseFloat(getComputedStyle(document.documentElement).fontSize)\n      const drift =\n        (Number.parseFloat(getComputedStyle(viewport).getPropertyValue(driftVariable)) ||\n          DRIFT_REM) * rem\n      const duration = roleDuration(viewport, 'layout') * (length / drift)\n      // No role's timing where it stands, such as outside a Kino theme: it stands still.\n      if (!(duration > 0)) return\n      animation = track.animate(\n        [{ translate: '0 0' }, { translate: `${rtl ? length : -length}px 0` }],\n        {\n          id: FOLLOWS_TRANSITION,\n          duration,\n          iterations: Infinity,\n          easing: 'linear',\n          direction: reverse ? 'reverse' : 'normal',\n        },\n      )\n      animation.currentTime = progress * duration\n      apply()\n    }\n    build()\n    const resize = new ResizeObserver(build)\n    resize.observe(track)\n    resize.observe(viewport)\n    const sight = new IntersectionObserver(([entry]) => {\n      seen = entry.isIntersecting\n      apply()\n    })\n    sight.observe(viewport)\n    // A feel, a motion preference or a direction set anywhere on the page rebuilds it, as it restyles CSS.\n    const preferences = new MutationObserver(build)\n    preferences.observe(document.documentElement, {\n      subtree: true,\n      attributeFilter: ['data-feel', 'data-motion', 'dir'],\n    })\n    const media = window.matchMedia('(prefers-reduced-motion: reduce)')\n    media.addEventListener('change', build)\n    control.current = (play) => {\n      wanted = play\n      apply()\n    }\n    return () => {\n      control.current = null\n      resize.disconnect()\n      sight.disconnect()\n      preferences.disconnect()\n      media.removeEventListener('change', build)\n      animation?.cancel()\n    }\n  }, [\n    viewportRef,\n    shiftRef,\n    trackRef,\n    copyRef,\n    leadRef,\n    reverse,\n    driftVariable,\n    setCopies,\n  ])\n  return { control, still }\n}\n\n/** One set of the items' length along the row: from the first item's start to the copies' start, gap included. */\nfunction setWidth(track: HTMLElement, copy: HTMLElement, rtl: boolean) {\n  const first = track.firstElementChild?.getBoundingClientRect()\n  const copies = copy.getBoundingClientRect()\n  if (!first) return 0\n  return rtl ? first.right - copies.right : copies.left - first.left\n}\n\n/** How far the first item stands from the track's start, in px. */\nfunction firstOffset(track: HTMLElement, rtl: boolean) {\n  const first = track.firstElementChild?.getBoundingClientRect()\n  const box = track.getBoundingClientRect()\n  if (!first) return 0\n  return rtl ? box.right - first.right : first.left - box.left\n}\n\n/** How far through its loop an animation is, from 0 to 1. */\nfunction progressOf(animation: Animation) {\n  const duration = Number(animation.effect?.getTiming().duration) || 0\n  const time = Number(animation.currentTime) || 0\n  if (!(duration > 0)) return 0\n  return (time % duration) / duration\n}\n\n/** Whether a row lays out right to left. */\nfunction isRtl(element: Element) {\n  return getComputedStyle(element).direction === 'rtl'\n}\n\n/** An element's `translate` along the row, in px. */\nfunction translateX(element: Element) {\n  return Number.parseFloat(getComputedStyle(element).translate) || 0\n}\n\n/** A box along the row, in px. */\ninterface Box {\n  start: number\n  end: number\n}\n\n/**\n * How far to move a row so an item in it stands clear of the faded ends,\n * its start first when it can't clear both, and never so far that the track\n * leaves the row's end empty. Boxes are along the row, in px.\n */\nfunction clearShift({\n  row,\n  track,\n  item,\n  fade,\n  rtl,\n}: {\n  row: Box\n  track: Box\n  item: Box\n  fade: number\n  rtl: boolean\n}) {\n  const room = { start: row.start + fade, end: row.end - fade }\n  let shift = 0\n  // Start and end as the page reads: in right to left the start is on the right.\n  const before = rtl ? item.end - room.end : room.start - item.start\n  const after = rtl ? room.start - item.start : item.end - room.end\n  if (before > 0) shift = rtl ? -before : before\n  else if (after > 0) shift = rtl ? Math.min(after, -before) : -Math.min(after, -before)\n  // The track must still cover the row from end to end.\n  return Math.min(Math.max(shift, row.end - track.end), row.start - track.start)\n}\n\n/**\n * Brings an item that took focus clear of the row's faded ends: the row\n * holds while an item has focus, and the wrapper around its track glides by\n * the difference on `layout`. The item is the track's child that holds the\n * focus.\n */\nfunction bringClear(target: Element) {\n  const row = target.closest<HTMLElement>('[data-slot=marquee-row]')\n  const shift = row?.querySelector<HTMLElement>('[data-slot=marquee-shift]')\n  const track = shift?.firstElementChild\n  const item = track ? [...track.children].find((child) => child.contains(target)) : null\n  const lead = track?.lastElementChild\n  if (!row || !shift || !track || !item || !lead) return\n  const along = (box: DOMRect) => ({ start: box.left, end: box.right })\n  const span = (a: Box, b: Box) => ({\n    start: Math.min(a.start, b.start),\n    end: Math.max(a.end, b.end),\n  })\n  const rowBox = along(row.getBoundingClientRect())\n  // As `--marquee-fade` works it out: 6rem, or 12% of a narrow row.\n  const fade = Math.min(\n    Number.parseFloat(getComputedStyle(document.documentElement).fontSize) * 6,\n    (rowBox.end - rowBox.start) * 0.12,\n  )\n  const by = clearShift({\n    row: rowBox,\n    // With the copy before the items, which covers the row's start as the drift would.\n    track: span(\n      along(track.getBoundingClientRect()),\n      along(lead.getBoundingClientRect()),\n    ),\n    item: along(item.getBoundingClientRect()),\n    fade,\n    rtl: isRtl(row),\n  })\n  if (Math.abs(by) < 0.5) return\n  shift.style.translate = `${translateX(shift) + by}px 0`\n}\n\n/**\n * As the drift plays again, takes the wrapper's shift into the drift's\n * clock, in one frame, so the row goes on from where it stands with no\n * offset left that could leave an end empty.\n */\nfunction settleShift(\n  animation: Animation,\n  shift: HTMLElement,\n  track: HTMLElement,\n  rtl: boolean,\n) {\n  const by = translateX(shift)\n  if (Math.abs(by) < 0.5) return\n  const timing = animation.effect?.getTiming()\n  const duration = Number(timing?.duration) || 0\n  const length = Math.abs(\n    Number.parseFloat(\n      String((animation.effect as KeyframeEffect).getKeyframes().at(-1)?.translate),\n    ),\n  )\n  if (!(duration > 0) || !(length > 0)) return\n  // Where the track will stand, as a share of a set's length: 0 at the keyframes' start, 1 a set along.\n  const value = translateX(track) + by\n  const along = rtl ? value : -value\n  const share = (((along % length) + length) % length) / length\n  const progress = timing?.direction === 'reverse' ? 1 - share : share\n  withoutTransition(shift, () => {\n    shift.style.translate = ''\n  })\n  animation.currentTime = progress * duration\n}\n\nexport { clearShift, copiesToFill, dealRows, MarqueeRow }\n",
      "type": "registry:lib",
      "target": "@lib/marquee.tsx"
    }
  ],
  "type": "registry:lib"
}