{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "scroll",
  "title": "Scroll",
  "description": "What a box that scrolls shows about it: its edges fade while content is hidden past them, a row keeps its picked or focused item in view, an item held at the top while what is above it closes, it takes focus as a named region while its content is larger than it, and a move linked to the page’s scroll. Tabs, the Segmented control, the Accordion, the panels, Table, Scroll area and the Hero blocks share it.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/theme.json",
    "https://kinoui.com/r/resize.json"
  ],
  "files": [
    {
      "path": "registry/lib/scroll.ts",
      "content": "'use client'\n\nimport { reducesMotion } from '@/registry/lib/reduce-motion'\nimport { roleDuration, runningTransitions, transitionsQuiet } from '@/registry/lib/resize'\nimport {\n  type RefCallback,\n  type RefObject,\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useState,\n} from 'react'\n\n/*\n * What a box that scrolls shows about it: its edges fade while content is\n * hidden past them, as the Tabs' list, a wide Table and a Scroll area do, and\n * it takes focus while its content is larger than it, so the keyboard can\n * scroll it, as a panel's body and a Table do. And what moves as the page\n * scrolls past it, as the Hero's product shot does.\n */\n\nconst EDGE_FADE_PX = 24\n\n/**\n * The nearest box that scrolls `element` up and down, or `null` when it's\n * the page: one whose overflow scrolls and whose content is taller than it.\n */\nexport function scrollerOf(element: Element): HTMLElement | null {\n  for (let node = element.parentElement; node; node = node.parentElement) {\n    const { overflowY } = getComputedStyle(node)\n    if (/(auto|scroll)/.test(overflowY) && node.scrollHeight > node.clientHeight)\n      return node\n  }\n  return null\n}\n\n/** How much of the next item shows past one that scrolled into view, in pixels. */\nconst REVEAL_PEEK_PX = 32\n\n/**\n * How wide each edge's fade is, in pixels, for a box scrolled `scrollLeft`\n * of `max`: only as wide as what is hidden past it, up to 24px. In right to\n * left the browser counts `scrollLeft` from 0 down to `-max`.\n */\nexport function edgeFades(scrollLeft: number, max: number, rtl: boolean) {\n  const left = rtl ? max + scrollLeft : scrollLeft\n  // A scroll position can rest a fraction of a pixel short of its end.\n  const fade = (hidden: number) => (hidden <= 1 ? 0 : Math.min(hidden, EDGE_FADE_PX))\n  return { left: fade(left), right: fade(max - left) }\n}\n\n/**\n * Each of a box's four edges' fade, in pixels, from its scroll position and\n * how far it can scroll each way. Right to left mirrors the sides only: a box\n * scrolls down from its top in either direction.\n */\nexport function boxEdgeFades(\n  box: { scrollLeft: number; scrollTop: number; maxX: number; maxY: number },\n  rtl: boolean,\n) {\n  const { left, right } = edgeFades(box.scrollLeft, box.maxX, rtl)\n  const { left: top, right: bottom } = edgeFades(box.scrollTop, box.maxY, false)\n  return { left, right, top, bottom }\n}\n\n/**\n * Writes each edge's fade on `scroller` as `<name>-left`, `<name>-right`,\n * `<name>-top` and `<name>-bottom` (`--tabs-fade-left`), for a mask to read,\n * its visible width as\n * `--scroller-width`, for what must stay in view as it scrolls sideways (a\n * caption), and marks it `data-scrolled`\n * while it is scrolled down from its top, for a sticky header to show it,\n * and `data-edge-start` and `data-edge-end` while content is hidden past\n * that side, with `<name>-start` and `<name>-end` as its fades, for a sticky\n * column to draw its edge and a mask to leave that side alone.\n * It follows the scroll and any change of size of the box or of `content`.\n * Returns a function that stops following.\n */\nexport function followEdges(\n  scroller: HTMLElement,\n  name: `--${string}`,\n  content: Element | null = scroller.firstElementChild,\n): () => void {\n  // What was last written, so a scroll that changes nothing restyles nothing.\n  const written = new Map<string, string>()\n  const write = (property: string, value: string) => {\n    if (written.get(property) === value) return\n    written.set(property, value)\n    scroller.style.setProperty(property, value)\n  }\n  // Read when the box is laid out again or a `dir` changes, never on a scroll,\n  // where a style read would restyle the page each frame.\n  let rtl = getComputedStyle(scroller).direction === 'rtl'\n  // Read once a frame, after whatever else moves the scroll in it, such as a thread\n  // that follows its end: a fade that shows and goes again within the frame\n  // restyles everything inside the scroller twice for nothing.\n  let frame = 0\n  const later = () => {\n    if (frame === 0)\n      frame = requestAnimationFrame(() => {\n        frame = 0\n        update()\n      })\n  }\n  const reread = () => {\n    rtl = getComputedStyle(scroller).direction === 'rtl'\n    later()\n  }\n  const update = () => {\n    // Every read before any write, which would make the next read lay the page out again.\n    const width = scroller.clientWidth\n    const scrollTop = scroller.scrollTop\n    const { left, right, top, bottom } = boxEdgeFades(\n      {\n        scrollLeft: scroller.scrollLeft,\n        scrollTop,\n        maxX: scroller.scrollWidth - width,\n        maxY: scroller.scrollHeight - scroller.clientHeight,\n      },\n      rtl,\n    )\n    write(`${name}-left`, `${left}px`)\n    write(`${name}-right`, `${right}px`)\n    write(`${name}-top`, `${top}px`)\n    write(`${name}-bottom`, `${bottom}px`)\n    write('--scroller-width', `${width}px`)\n    scroller.toggleAttribute('data-scrolled', scrollTop > 0)\n    // Which sides hide content past them, for what is pinned to that side to draw an edge.\n    scroller.toggleAttribute('data-edge-start', (rtl ? right : left) > 0)\n    scroller.toggleAttribute('data-edge-end', (rtl ? left : right) > 0)\n    write(`${name}-start`, `${rtl ? right : left}px`)\n    write(`${name}-end`, `${rtl ? left : right}px`)\n  }\n  update()\n  scroller.addEventListener('scroll', later, { passive: true })\n  const resized = new ResizeObserver(reread)\n  resized.observe(scroller)\n  if (content) resized.observe(content)\n  const turned = new MutationObserver(reread)\n  turned.observe(document.documentElement, {\n    attributes: true,\n    attributeFilter: ['dir'],\n    subtree: true,\n  })\n  return () => {\n    scroller.removeEventListener('scroll', later)\n    cancelAnimationFrame(frame)\n    resized.disconnect()\n    turned.disconnect()\n  }\n}\n\n/**\n * The mask that fades a scroller's edges while content is hidden past them,\n * on the variables `useEdgeFades` writes. Its scroll padding is the fade's\n * width, so a row the keyboard brings into view stops clear of the fade.\n * It masks the whole box, so it goes on an inner scroller, never on a\n * surface with a shadow, a ring or an outline, and a scroller that takes\n * focus draws its ring on the box around it (`scrollRegionRingClassName`).\n */\nexport const edgeFadeClassName =\n  'scroll-py-6 [mask-image:linear-gradient(to_right,transparent,black_var(--scroll-fade-left,0px),black_calc(100%-var(--scroll-fade-right,0px)),transparent),linear-gradient(to_bottom,transparent,black_var(--scroll-fade-top,0px),black_calc(100%-var(--scroll-fade-bottom,0px)),transparent)] [mask-composite:intersect]'\n\n/** A ref for a scroller with `edgeFadeClassName`: its edges fade while there is more past them. */\nexport function useEdgeFades<Scroller extends HTMLElement>(): RefCallback<Scroller> {\n  return useCallback(\n    (scroller: Scroller | null) =>\n      scroller ? followEdges(scroller, '--scroll-fade') : undefined,\n    [],\n  )\n}\n\n/**\n * The focus ring of a scroll region, for the box around it: drawn over the\n * region's content, which would cover a ring of its own, and inside the box,\n * which may clip what is outside. Forced colours draw it as an outline.\n */\nexport const scrollRegionRingClassName =\n  'relative after:pointer-events-none after:absolute after:inset-0 after:z-40 after:rounded-[inherit] has-[>[role=region]:focus-visible]:after:ring-3 has-[>[role=region]:focus-visible]:after:ring-ring/50 has-[>[role=region]:focus-visible]:after:ring-inset forced-colors:has-[>[role=region]:focus-visible]:after:outline-2 forced-colors:has-[>[role=region]:focus-visible]:after:-outline-offset-2'\n\n/** Whether a box's content is larger than the box, by more than a rounding error, either way. */\nexport function overflows(box: {\n  scrollWidth: number\n  clientWidth: number\n  scrollHeight: number\n  clientHeight: number\n}) {\n  return box.scrollWidth - box.clientWidth > 1 || box.scrollHeight - box.clientHeight > 1\n}\n\n/**\n * The props of a box while its content is larger than it: it takes focus,\n * or the keyboard couldn't scroll it, as a region named by the element whose\n * id `labelledBy` finds. `axis` is the way it scrolls. When it stops\n * scrolling while focused, focus moves to what `refocus` finds, so it isn't\n * lost.\n */\nexport function useScrollRegion(\n  scrollerRef: RefObject<HTMLElement | null>,\n  {\n    contentRef,\n    axis = 'y',\n    labelledBy,\n    refocus,\n  }: {\n    contentRef?: RefObject<HTMLElement | null>\n    axis?: 'x' | 'y' | 'both'\n    labelledBy: (scroller: HTMLElement) => string | null | undefined\n    refocus?: (scroller: HTMLElement) => HTMLElement | null | undefined\n  },\n) {\n  const [scrolls, setScrolls] = useState(false)\n  const [labelId, setLabelId] = useState<string>()\n\n  // Before the first paint, so it is there when a dialog picks what to focus.\n  useLayoutEffect(() => {\n    const scroller = scrollerRef.current\n    if (!scroller) return\n    const measure = () => {\n      const scrolls = overflows({\n        scrollWidth: axis === 'y' ? scroller.clientWidth : scroller.scrollWidth,\n        clientWidth: scroller.clientWidth,\n        scrollHeight: axis === 'x' ? scroller.clientHeight : scroller.scrollHeight,\n        clientHeight: scroller.clientHeight,\n      })\n      // It is about to lose its place in the tab order: focus stays nearby.\n      if (!scrolls && document.activeElement === scroller) {\n        refocus?.(scroller)?.focus({ preventScroll: true })\n      }\n      setScrolls(scrolls)\n      setLabelId(labelledBy(scroller) ?? undefined)\n    }\n    measure()\n    const observer = new ResizeObserver(measure)\n    observer.observe(scroller)\n    const content = contentRef?.current ?? scroller.firstElementChild\n    if (content) observer.observe(content)\n    return () => observer.disconnect()\n  }, [scrollerRef, contentRef, axis, labelledBy, refocus])\n\n  return scrolls\n    ? ({ role: 'region', 'aria-labelledby': labelId, tabIndex: 0 } as const)\n    : undefined\n}\n\n/** Frames with nothing moving before an element held at the top is let go. */\nconst SETTLE_FRAMES = 4\n\n/**\n * The line an element held at the top of its scroller stops at, in the\n * viewport: the scroller's top, lowered by its `scroll-padding-top` (a sticky\n * header) and the element's `scroll-margin-top`, and `gap` more.\n */\nexport function topEdge(element: Element, gap = 0): number {\n  const scroller = scrollerOf(element)\n  return (\n    (scroller ? scroller.getBoundingClientRect().top : 0) +\n    topInset(element, scroller) +\n    gap\n  )\n}\n\n/**\n * How far below its scroller's top (the page's, without one) an element\n * scrolled to the top stops: the scroller's `scroll-padding-top`, for a\n * sticky header, and the element's `scroll-margin-top`, in pixels.\n */\nexport function topInset(element: Element, scroller: Element | null): number {\n  return (\n    (Number.parseFloat(\n      getComputedStyle(scroller ?? document.documentElement).scrollPaddingTop,\n    ) || 0) + (Number.parseFloat(getComputedStyle(element).scrollMarginTop) || 0)\n  )\n}\n\n/**\n * Keeps `element` from rising past `line` while heights inside `watch` move,\n * as answers above it close: it rides up to the line and waits there while\n * its scroller scrolls under it. A scroll on its way to it goes on until the\n * element reaches the line. It lets go once nothing has moved for a few\n * frames. Kept outside components: the React Compiler drops the forced reads\n * written inside one.\n */\nexport function holdAtEdge(element: Element, watch: Element, line: number) {\n  const scroller = scrollerOf(element)\n  whileHeightsMove(watch, scroller, () => {\n    if (!element.isConnected) return false\n    const over = element.getBoundingClientRect().top - line\n    if (over < -0.5) (scroller ?? window).scrollBy({ top: over, behavior: 'instant' })\n    return true\n  })\n}\n\n/** Whether a height transition runs on `watch` or inside it. */\nfunction heightsMoving(watch: Element) {\n  return runningTransitions(watch, { property: 'height', subtree: true }).length > 0\n}\n\n/**\n * Calls `step` once a frame, from the next, while heights inside `watch`\n * move or `scroller` (the page, when null) scrolls, and stops once nothing\n * has moved for a few frames, or when `step` returns false. A step sees each\n * frame of a height transition, so what it keeps in place never lags one.\n * Returns a function that stops it sooner, and when it has stopped.\n */\nfunction whileHeightsMove(\n  watch: Element,\n  scroller: Element | null,\n  step: () => boolean,\n): { stop: () => void; stopped: Promise<void> } {\n  const position = () => (scroller ? scroller.scrollTop : window.scrollY)\n  let last = position()\n  let quiet = 0\n  let frame = 0\n  let end = () => {}\n  const stopped = new Promise<void>((resolve) => {\n    end = resolve\n  })\n  const tick = () => {\n    if (!step()) return end()\n    const now = position()\n    const moving = now !== last || heightsMoving(watch)\n    last = now\n    quiet = moving ? 0 : quiet + 1\n    if (quiet < SETTLE_FRAMES) frame = requestAnimationFrame(tick)\n    else end()\n  }\n  frame = requestAnimationFrame(tick)\n  return {\n    stop: () => {\n      cancelAnimationFrame(frame)\n      end()\n    },\n    stopped,\n  }\n}\n\n/**\n * How far to scroll a row so an item shows with 32px of its neighbour, in\n * pixels (negative scrolls left); 0 when it already does. An item wider\n * than the row keeps its own start in view.\n */\nexport function revealBy(\n  row: { left: number; right: number },\n  item: { left: number; right: number },\n) {\n  const before = item.left - row.left - REVEAL_PEEK_PX\n  const after = item.right - row.right + REVEAL_PEEK_PX\n  const by = before < 0 ? before : after > 0 ? Math.min(after, before) : 0\n  return Math.abs(by) < 1 ? 0 : by\n}\n\n/**\n * How far to scroll a list down (negative scrolls up) to bring an item in\n * sight: as `revealBy` does when some of it shows, so an item in view stays\n * put and one an edge or its fade cuts moves just clear of it, and to the\n * list's middle when none of it shows.\n */\nexport function bringIntoSightBy(\n  list: { top: number; bottom: number },\n  item: { top: number; bottom: number },\n) {\n  if (item.bottom <= list.top || item.top >= list.bottom)\n    return (item.top + item.bottom) / 2 - (list.top + list.bottom) / 2\n  return revealBy(\n    { left: list.top, right: list.bottom },\n    { left: item.top, right: item.bottom },\n  )\n}\n\n/**\n * The scroll jumps when motion is reduced, by the device or by the motion\n * preference (`data-motion='reduce'`, as the `motion-reduce:` variant reads\n * it), or when the morph role takes no time: `instant`, never `auto`, which\n * would take a `scroll-behavior: smooth` set on the scroller.\n */\nexport function revealBehavior(scroller: HTMLElement): ScrollBehavior {\n  const reduced =\n    reducesMotion(scroller) || roleDuration(scroller, 'morph', Number.NaN) === 0\n  return reduced ? 'instant' : 'smooth'\n}\n\n/**\n * Scrolls `element` into sight once it and every box around it stop moving,\n * so an item that glides into a list, or into a column that is opening,\n * comes into view where it lands rather than where it is on the way.\n */\nexport async function revealOnceStill(element: HTMLElement): Promise<void> {\n  const boxes: Element[] = []\n  for (let box: Element | null = element; box; box = box.parentElement) boxes.push(box)\n  await Promise.all(boxes.map((box) => transitionsQuiet(box)))\n  if (!element.isConnected) return\n  element.scrollIntoView({\n    block: 'nearest',\n    inline: 'nearest',\n    behavior: revealBehavior(element),\n  })\n}\n\nfunction reveal(scroller: HTMLElement, item: Element | null, behavior: ScrollBehavior) {\n  if (!item || scroller.scrollWidth <= scroller.clientWidth) return\n  const left = revealBy(scroller.getBoundingClientRect(), item.getBoundingClientRect())\n  if (left !== 0) scroller.scrollBy({ left, behavior })\n}\n\n/**\n * For a row of items that outgrows its column, as the Tabs' list and a\n * range's two dates: fades the edges as `followEdges` does, and scrolls the\n * picked item (the one that gains `picked`, such as `data-active`) or the\n * focused one into view with a little of its neighbour, so the next can be\n * seen. Returns a function that stops following.\n */\nexport function revealInRow(\n  scroller: HTMLElement,\n  { item, picked, fade }: { item: string; picked?: string; fade: `--${string}` },\n): () => void {\n  const pickedNow = new MutationObserver((records) => {\n    for (const { target } of records) {\n      if (\n        target instanceof Element &&\n        picked &&\n        target.matches(item) &&\n        target.hasAttribute(picked)\n      ) {\n        reveal(scroller, target, revealBehavior(scroller))\n      }\n    }\n  })\n  if (picked)\n    pickedNow.observe(scroller, {\n      attributes: true,\n      attributeFilter: [picked],\n      subtree: true,\n    })\n  const focused = (event: FocusEvent) => {\n    if (event.target instanceof Element) {\n      reveal(scroller, event.target.closest(item), revealBehavior(scroller))\n    }\n  }\n  scroller.addEventListener('focusin', focused)\n  const stopEdges = followEdges(scroller, fade)\n  if (picked) reveal(scroller, scroller.querySelector(`${item}[${picked}]`), 'instant')\n  return () => {\n    pickedNow.disconnect()\n    stopEdges()\n    scroller.removeEventListener('focusin', focused)\n  }\n}\n\n/**\n * Where a scroll-linked move starts and ends, in px of scrolling: it starts\n * when the element's top is `from` of the way down the scroller's view (1 is\n * its bottom edge) and ends at `to`. A move that would start before the top\n * of the page starts there, so an element at the top of a page begins it from\n * its first state. Nothing, when the page can't scroll far enough for the\n * move to read as one.\n */\nexport function scrollLinkedRange({\n  top,\n  view,\n  max,\n  from,\n  to,\n}: {\n  /** The element's top, in px from the start of the scroller's content. */\n  top: number\n  /** The scroller's visible height, in px. */\n  view: number\n  /** How far the scroller scrolls, in px. */\n  max: number\n  from: number\n  to: number\n}): { start: number; end: number } | null {\n  if (max <= 0 || view <= 0) return null\n  const start = Math.round(Math.min(max, Math.max(0, top - from * view)))\n  const end = Math.round(Math.min(max, Math.max(0, top - to * view)))\n  // Less than a tenth of a screen of scrolling would make it a jump.\n  if (end - start < view * 0.1) return null\n  return { start, end }\n}\n\n/**\n * A move that only slides, from `from` to `to` (each a translation in CSS\n * px), set on whole device pixels: both ends rounded to one at `ratio` device\n * pixels per CSS pixel, and how many steps of one device pixel the move takes\n * along its longer axis. A layer the compositor moves by a fraction of a\n * pixel is resampled and its text goes soft, so a slow drift steps from pixel\n * to pixel instead. Nothing when it doesn't move a whole pixel.\n */\nexport function pixelSteps(\n  from: { x: number; y: number },\n  to: { x: number; y: number },\n  ratio: number,\n): {\n  from: { x: number; y: number }\n  to: { x: number; y: number }\n  steps: number\n} | null {\n  const snap = (value: number) => Math.round(value * ratio) / ratio\n  const start = { x: snap(from.x), y: snap(from.y) }\n  const end = { x: snap(to.x), y: snap(to.y) }\n  const steps = Math.round(\n    Math.max(Math.abs(end.x - start.x), Math.abs(end.y - start.y)) * ratio,\n  )\n  return steps > 0 ? { from: start, to: end, steps } : null\n}\n\n/** Where `frame` would put `element`, when all it does is slide it; otherwise `null`. */\nfunction translationOf(element: HTMLElement, frame: Keyframe) {\n  const probe = element.animate([frame], { fill: 'forwards' })\n  const transform = getComputedStyle(element).transform\n  probe.cancel()\n  const matrix = new DOMMatrixReadOnly(transform === 'none' ? undefined : transform)\n  const slides =\n    matrix.is2D && matrix.a === 1 && matrix.b === 0 && matrix.c === 0 && matrix.d === 1\n  return slides ? { x: matrix.e, y: matrix.f } : null\n}\n\n/** A move's keyframes, on whole device pixels when it only slides at the scroll's own rate. */\nfunction keyframesOf(\n  element: HTMLElement,\n  start: Keyframe,\n  end: Keyframe,\n  easing: string,\n  ratio: number,\n): Keyframe[] {\n  const from = easing === 'linear' ? translationOf(element, start) : null\n  const to = from ? translationOf(element, end) : null\n  const stepped = from && to ? pixelSteps(from, to, ratio) : null\n  if (!stepped) return [{ ...start, easing }, { ...end }]\n  const at = ({ x, y }: { x: number; y: number }) => `translate(${x}px, ${y}px)`\n  return [\n    {\n      ...start,\n      transform: at(stepped.from),\n      // A level at each pixel from one end to the other, both ends included.\n      easing: `steps(${stepped.steps + 1}, jump-none)`,\n    },\n    { ...end, transform: at(stepped.to) },\n  ]\n}\n\n/** An element's top in the page, from layout alone, so a transform on it or above it doesn't move it. */\nfunction pageTop(element: HTMLElement) {\n  let top = 0\n  for (\n    let at: HTMLElement | null = element;\n    at;\n    at = at.offsetParent as HTMLElement | null\n  ) {\n    top += at.offsetTop\n  }\n  return top\n}\n\n/**\n * An element's top in its scroller's content, in pixels from the content's\n * start, from layout alone: the scroll position and any transform, such as\n * an entrance's rise, leave it where it is.\n */\nexport function contentTop(element: HTMLElement, scroller: HTMLElement) {\n  return pageTop(element) - pageTop(scroller) - scroller.clientTop\n}\n\n/**\n * Moves `ref`'s element from `from` to `to` as the page scrolls it into\n * view, on the scroll itself, off the main thread: a scroll timeline on the\n * element that actually scrolls it, never the nearest box that clips, which\n * would hold a `view()` timeline still. The move is placed again only when\n * where it starts or ends changes, and follows a feel or a reduced-motion\n * preference set after load. Where the page can't scroll far enough for the\n * move, the element rests at `to`. Where motion is reduced, or the browser has\n * no scroll timelines, nothing moves it: it rests where its own CSS puts it, so\n * a starting pose set in CSS for the first paint sits under\n * `motion-safe:supports-[animation-timeline:scroll()]:`. A move that only\n * slides, at the scroll's own rate, steps from one device pixel to the next,\n * so the text in it stays sharp wherever the scroll stops.\n */\nexport function useScrollLinked(\n  ref: RefObject<HTMLElement | null>,\n  {\n    from,\n    to,\n    range,\n    pace = 'settle',\n  }: {\n    from: Keyframe\n    to: Keyframe\n    /** Where the element's top sits in the view, as a share down it, when the move starts and ends. */\n    range: readonly [number, number]\n    /**\n     * How the move follows the scroll: `settle` on the `layout` role's curve\n     * without its overshoot, quick at first and easing into place, or `even`,\n     * at the scroll's own rate, for layers that drift at a depth.\n     */\n    pace?: 'settle' | 'even'\n  },\n) {\n  const [rangeFrom, rangeTo] = range\n  const fromKey = JSON.stringify(from)\n  const toKey = JSON.stringify(to)\n  useEffect(() => {\n    const element = ref.current\n    if (!element || typeof ScrollTimeline === 'undefined') return\n    const start = JSON.parse(fromKey) as Keyframe\n    const end = JSON.parse(toKey) as Keyframe\n    let animation: Animation | undefined\n    let placed = ''\n    let frame = 0\n    let watched = 0\n    let resolution: MediaQueryList | undefined\n\n    const place = () => {\n      // A box that scrolls it, or else the page.\n      const own = scrollerOf(element)\n      const scroller = own ?? document.scrollingElement ?? document.documentElement\n      const reduced = reducesMotion(element)\n      const offsets = reduced\n        ? null\n        : scrollLinkedRange({\n            top: own ? contentTop(element, own) : pageTop(element),\n            view: scroller.clientHeight,\n            max: scroller.scrollHeight - scroller.clientHeight,\n            from: rangeFrom,\n            to: rangeTo,\n          })\n      const easing =\n        pace === 'even'\n          ? 'linear'\n          : getComputedStyle(element)\n              .getPropertyValue('--motion-layout-fade-easing')\n              .trim()\n      // A screen of another density, or a zoom, moves the device pixels the move steps on.\n      const ratio = window.devicePixelRatio || 1\n      if (ratio !== watched) {\n        watched = ratio\n        resolution?.removeEventListener('change', schedule)\n        resolution = window.matchMedia(`(resolution: ${ratio}dppx)`)\n        resolution.addEventListener('change', schedule)\n      }\n      // Read again each time, so a distance set in a variable above it follows a change.\n      const keyframes = reduced\n        ? []\n        : keyframesOf(element, start, end, easing || 'linear', ratio)\n      const key = reduced\n        ? 'reduced'\n        : `${offsets && easing ? `${offsets.start} ${offsets.end}` : 'rest'} ${JSON.stringify(keyframes)}`\n      const timeline = timelines.get(scroller)\n      if (key === placed && (!offsets || animation?.timeline === timeline)) return\n      placed = key\n      animation?.cancel()\n      animation = undefined\n      if (reduced) return\n      if (!offsets || !easing) {\n        // Too little scroll for the move: it rests where it would end.\n        animation = element.animate([keyframes.at(-1) ?? end], {\n          fill: 'forwards',\n        })\n        return\n      }\n      // In scroll px, so content that grows below the element moves nothing.\n      const rangeStart = `${offsets.start}px`\n      const rangeEnd = `${offsets.end}px`\n      animation = element.animate(keyframes, {\n        timeline: timelineOf(scroller),\n        rangeStart,\n        rangeEnd,\n        fill: 'both',\n      })\n    }\n    // At most once a frame, however many changes arrive in it.\n    const schedule = () => {\n      cancelAnimationFrame(frame)\n      frame = requestAnimationFrame(place)\n    }\n\n    place()\n    // Where the move starts and ends shifts when anything changes size: the\n    // window, the page or the element.\n    const resizes = new ResizeObserver(schedule)\n    resizes.observe(element)\n    resizes.observe(document.body)\n    // The view's own height changes without the page's size: a phone's\n    // address bar, or a window made shorter.\n    window.addEventListener('resize', schedule)\n    // A feel or a reduced-motion preference can be set on any element above it.\n    const preferences = new MutationObserver(schedule)\n    preferences.observe(document.documentElement, {\n      attributes: true,\n      attributeFilter: ['data-feel', 'data-motion'],\n      subtree: true,\n    })\n    // So can a variable the move reads, such as how far it goes. An observer of\n    // its own: observing <html> again would replace the watch above.\n    const variables = new MutationObserver(schedule)\n    for (let above = element.parentElement; above; above = above.parentElement) {\n      variables.observe(above, {\n        attributes: true,\n        attributeFilter: ['style', 'class'],\n      })\n    }\n    const motion = window.matchMedia('(prefers-reduced-motion: reduce)')\n    motion.addEventListener('change', schedule)\n    return () => {\n      resizes.disconnect()\n      window.removeEventListener('resize', schedule)\n      preferences.disconnect()\n      variables.disconnect()\n      motion.removeEventListener('change', schedule)\n      resolution?.removeEventListener('change', schedule)\n      cancelAnimationFrame(frame)\n      animation?.cancel()\n    }\n  }, [ref, fromKey, toKey, rangeFrom, rangeTo, pace])\n}\n\n/** One scroll timeline per scroller, shared by every move it drives. */\nconst timelines = new WeakMap<Element, ScrollTimeline>()\n\nfunction timelineOf(scroller: Element) {\n  let timeline = timelines.get(scroller)\n  if (!timeline) {\n    timeline = new ScrollTimeline({ source: scroller, axis: 'block' })\n    timelines.set(scroller, timeline)\n  }\n  return timeline\n}\n",
      "type": "registry:lib",
      "target": "@lib/scroll.ts"
    }
  ],
  "type": "registry:lib"
}