{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "scroll-stage",
  "title": "Scroll Stage",
  "description": "A fixed stage whose pieces move, scale and fade by scroll position, replaying measured keyframe tracks per layout, with time-based fades and a text entrance. Needs gsap and @gsap/react.",
  "files": [
    {
      "path": "registry/mewo/ui/scroll-stage.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { cn } from \"@/lib/utils\"\n\n/** One keyframe: [scroll position in viewport heights, centre x (vw %), centre y (vh %), scale, opacity?]. */\nexport type StageKey = [number, number, number, number, number?]\n\n/** An element's motion: its layout size where it was measured, its keyframes, and windows where it fades by time. */\nexport type StageTrack = { size: [number, number]; keys?: StageKey[]; on?: [number, number][] }\n\n/** Every element's track for one layout; `_meta` is the viewport the set was measured at. */\nexport type StageTrackSet = Record<string, StageTrack> & { _meta?: { vw: number; vh: number } }\n\nexport type StageLayout = \"desktop\" | \"tablet\" | \"phone\"\n\nexport type StageState = {\n  /** Scroll position in viewport heights. */\n  progress: number\n  /** Scroll speed in viewport heights per second. */\n  velocity: number\n  layout: StageLayout\n  reducedMotion: boolean\n  /** The stage is mirrored left to right (a right-to-left page). */\n  mirror: boolean\n}\n\nconst QUERIES: Record<StageLayout, string> = {\n  desktop: \"(min-width: 901px)\",\n  tablet: \"(max-width: 900px) and (min-aspect-ratio: 13/20)\",\n  phone: \"(max-width: 900px) and (max-aspect-ratio: 13/20)\",\n}\n\n// The state lives outside React: the stage writes it on every scroll update, components read only what they select.\n// Each stage has its own store, so several stages on one page (demos in frames) don't mix; a stage that follows the\n// page's scroll also is the page's store, which getScrollStage reads.\ntype StageStore = { state: StageState; listeners: Set<() => void> }\nconst createStore = (): StageStore => ({\n  state: { progress: 0, velocity: 0, layout: \"desktop\", reducedMotion: false, mirror: false },\n  listeners: new Set(),\n})\nconst pageStore = createStore()\nconst emit = (store: StageStore) => store.listeners.forEach((l) => l())\nconst setStage = (store: StageStore, patch: Partial<StageState>, notify = true) => {\n  store.state = { ...store.state, ...patch }\n  if (notify) emit(store)\n}\n\n/** The page's stage state, for frame loops outside React (a WebGL layer, say). */\nexport function getScrollStage() {\n  return pageStore.state\n}\n\nconst StoreContext = React.createContext<StageStore | null>(null)\n\n/** Selects from the nearest stage's state; re-renders only when the selected value changes (select primitives). */\nexport function useScrollStage<T>(select: (s: StageState) => T): T {\n  const store = React.useContext(StoreContext) ?? pageStore\n  const subscribe = React.useCallback(\n    (l: () => void) => {\n      store.listeners.add(l)\n      return () => {\n        store.listeners.delete(l)\n      }\n    },\n    [store]\n  )\n  return React.useSyncExternalStore(subscribe, () => select(store.state), () => select(store.state))\n}\n\n/** True inside a ScrollStage: blocks lay their pieces out for the stage, and in normal flow elsewhere. */\nexport function useInScrollStage() {\n  return React.useContext(StoreContext) !== null\n}\n\n/** A track's values at scroll position v, linearly between keys: [cx, cy, scale, opacity] into out. */\nexport function sampleKeys(keys: StageKey[], v: number, out: number[]) {\n  let a = keys[0]!\n  let b = keys[0]!\n  let t = 0\n  const last = keys[keys.length - 1]!\n  if (v >= last[0]) {\n    a = last\n    b = last\n  } else if (v > a[0]) {\n    let lo = 0\n    let hi = keys.length - 1\n    while (hi - lo > 1) {\n      const m = (lo + hi) >> 1\n      if (keys[m]![0] <= v) lo = m\n      else hi = m\n    }\n    a = keys[lo]!\n    b = keys[hi]!\n    t = (v - a[0]) / (b[0] - a[0])\n  }\n  for (let i = 1; i <= 4; i++) {\n    const x = a[i] ?? 1\n    const y = b[i] ?? 1\n    out[i - 1] = x + (y - x) * t\n  }\n  return out\n}\n\n// Tracked pieces sit at the stage's top left and are moved by translate + scale. Until the stage is ready, and when\n// the layout has no track for them, they stay hidden. Pieces with time-based fades (data-timed) fade when the stage\n// sets data-on; story text marked data-entrance fades out first, then fades in while growing from 0.9 (fast at\n// first, then ever slower over five seconds), so two texts in one place never overlap.\nconst STAGE = [\n  \"pointer-events-none fixed inset-0 overflow-hidden\",\n  \"[&_[data-track]]:absolute [&_[data-track]]:top-0 [&_[data-track]]:left-0 [&_[data-track]]:origin-center [&_[data-track]]:will-change-transform\",\n  \"[&:not([data-ready])_[data-track]]:invisible [&_[data-untracked]]:invisible\",\n  \"[&_[data-timed]]:invisible [&_[data-timed]]:opacity-0 [&_[data-timed]]:[transition:opacity_0.8s_cubic-bezier(0.455,0.03,0.515,0.955),visibility_0s_linear_0.8s]\",\n  \"[&_[data-timed][data-on]]:visible [&_[data-timed][data-on]]:opacity-100 [&_[data-timed][data-on]]:[transition:opacity_0.8s_cubic-bezier(0.455,0.03,0.515,0.955),visibility_0s]\",\n  \"[&_[data-timed][data-entrance]]:scale-90 [&_[data-timed][data-entrance]]:[transition:opacity_0.22s_ease-in,scale_0s_linear_0.22s,visibility_0s_linear_0.22s]\",\n  \"[&_[data-timed][data-entrance][data-on]]:scale-100 [&_[data-timed][data-entrance][data-on]]:[transition:opacity_1.2s_cubic-bezier(0.215,0.61,0.355,1)_0.25s,scale_5s_cubic-bezier(0.19,1,0.22,1)_0.25s,visibility_0s]\",\n].join(\" \")\n\ntype Bound = {\n  el: HTMLElement\n  track: StageTrack\n  w: number\n  h: number\n  x: number\n  y: number\n  s: number\n  parent?: Bound\n  below?: Bound\n  last: string\n}\n\n// Two pieces for the demo: a title that rises and shrinks, and a caption that fades in by time.\nconst DEMO_TRACKS: Partial<Record<StageLayout, StageTrackSet>> = {\n  desktop: {\n    title: { size: [600, 120], keys: [[0, 50, 50, 1, 1], [1, 50, 25, 0.6, 1], [2, 50, 10, 0.4, 0]] },\n    caption: { size: [500, 60], keys: [[0, 50, 70, 1]], on: [[0.4, 1.6]] },\n  },\n}\n\nexport interface ScrollStageProps extends React.ComponentProps<\"div\"> {\n  /** Keyframe tracks per layout (desktop above 900px, tablet and phone below it, split at an aspect of 13/20). */\n  tracks?: Partial<Record<StageLayout, StageTrackSet>>\n  /** Length of the story in viewport heights; the page itself must be at least this tall. */\n  length?: number\n  /** Media queries that choose each layout's track set. */\n  queries?: Partial<Record<StageLayout, string>>\n  /** Mirror every piece left to right, for right-to-left pages: a text on the left of the picture moves to its right. */\n  mirror?: boolean\n  /** An element that scrolls instead of the page (a demo's box): the stage follows its scroll, and measures its own box\n   * instead of the window. Hold the stage inside a size-contained box (`container-type: size` and `contain: layout`) so `fixed` keeps it there. */\n  scroller?: React.RefObject<HTMLElement | null>\n  /** Use this layout's tracks whatever the window (a demo frame shows the desktop story at any width). */\n  layout?: StageLayout\n}\n\n/**\n * A fixed stage whose pieces (`data-track=\"<name>\"`) move, scale and fade by scroll position, replaying keyframe\n * tracks. Pieces can also fade by time inside `on` windows, sit under another piece (`data-track-below`), keep their\n * top edge (`data-track-anchor=\"top\"`) or move inside a parent piece (`data-track-rel`). Writes `--s` (the scale) so\n * CSS can shade a picture as it zooms.\n */\nexport function ScrollStage({ tracks = DEMO_TRACKS, length = 3, queries, mirror = false, scroller, layout: forced, className, children, ...props }: ScrollStageProps) {\n  const root = React.useRef<HTMLDivElement>(null)\n  const [ownStore] = React.useState(createStore)\n  const store = scroller ? ownStore : pageStore\n\n  // The stage works only when something happens: a scroll or a resize schedules one frame that moves every piece,\n  // and nothing runs between events, on screen or off.\n  React.useEffect(() => {\n    const el = root.current\n    if (!el) return\n    setStage(store, { reducedMotion: window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches ?? false, mirror }, false)\n    const scrollerEl = scroller?.current ?? null\n    const target: EventTarget = scrollerEl ?? window\n    // the stage's box: the window's, or (following a scroller) its own\n    const W = () => (scrollerEl ? el.clientWidth : window.innerWidth)\n    const H = () => (scrollerEl ? el.clientHeight : window.innerHeight)\n    // the scroll position in viewport heights, held inside the story\n    const position = () => Math.min(length, Math.max(0, (scrollerEl ? scrollerEl.scrollTop : window.scrollY) / Math.max(1, H())))\n\n    let alive = true\n    const setup = (layout: StageLayout) => {\n      setStage(store, { layout })\n      const set = tracks[layout] ?? tracks.desktop ?? {}\n      const traceVh = set._meta?.vh || 900\n      const bound: Bound[] = []\n      for (const node of el.querySelectorAll<HTMLElement>(\"[data-track]\")) {\n        const track = set[node.dataset.track!] as StageTrack | undefined\n        node.toggleAttribute(\"data-untracked\", !track)\n        if (!track) continue\n        node.toggleAttribute(\"data-timed\", !!track.on)\n        const b: Bound = { el: node, track, w: 0, h: 0, x: 0, y: 0, s: 1, last: \"\" }\n        if (node.dataset.trackRel) b.parent = bound.find((p) => p.el === node.parentElement?.closest(\"[data-track]\"))\n        if (node.dataset.trackBelow) b.below = bound.find((p) => p.el.dataset.track === node.dataset.trackBelow)\n        bound.push(b)\n      }\n      const measure = () => {\n        for (const b of bound) {\n          b.w = b.el.offsetWidth\n          b.h = b.el.offsetHeight\n          b.last = \"\"\n        }\n      }\n      const v4 = [0, 0, 1, 1]\n      const apply = (v: number) => {\n        const vw = W() / 100\n        const vh = H() / 100\n        for (const b of bound) {\n          if (!b.track.keys) continue\n          sampleKeys(b.track.keys, v, v4)\n          const [cx, cy, s, o] = v4 as [number, number, number, number]\n          let x = (mirror ? 100 - cx : cx) * vw - b.w / 2\n          let y = cy * vh - b.h / 2\n          if (b.el.dataset.trackAnchor === \"top\") y = cy * vh - (b.track.size[1] * s * (H() / traceVh)) / 2\n          // a credit under a picture whose box is sized in vw: a measured vh position would land on it at other aspects\n          if (b.below) y = b.below.y + (b.below.h * (1 + b.below.s)) / 2 + vh\n          b.x = x\n          b.y = y\n          b.s = s\n          if (b.parent) {\n            x -= b.parent.x\n            y -= b.parent.y\n          }\n          const key = `${x.toFixed(1)}|${y.toFixed(1)}|${s.toFixed(4)}|${o.toFixed(3)}`\n          if (key === b.last) continue\n          b.last = key\n          // position through `translate`, so a CSS `scale` on the piece (the text entrance) scales it about its centre\n          b.el.style.translate = `${x.toFixed(2)}px ${y.toFixed(2)}px`\n          b.el.style.transform = `scale(${s.toFixed(4)})`\n          b.el.style.setProperty(\"--s\", s.toFixed(4))\n          if (b.track.keys[0]!.length > 4) {\n            b.el.style.opacity = o.toFixed(3)\n            b.el.style.visibility = o < 0.002 ? \"hidden\" : \"visible\"\n          }\n        }\n      }\n      // a timed piece is on while the position is inside one of its windows; the CSS fades do the rest\n      const timed = bound.filter((b) => b.track.on)\n      const toggle = (v: number) => {\n        for (const b of timed) b.el.toggleAttribute(\"data-on\", b.track.on!.some(([from, to]) => v >= from && v < to))\n      }\n\n      let last = position()\n      let lastAt = performance.now()\n      let frame = 0\n      let still = 0\n      const update = () => {\n        frame = 0\n        const now = performance.now()\n        const v = position()\n        const dt = Math.max(1 / 240, (now - lastAt) / 1000)\n        setStage(store, { progress: v, velocity: (v - last) / dt }, false)\n        last = v\n        lastAt = now\n        apply(v)\n        toggle(v)\n        emit(store)\n        // the speed reads 0 once the scroll has stopped\n        window.clearTimeout(still)\n        still = window.setTimeout(() => setStage(store, { velocity: 0 }), 150)\n      }\n      const schedule = () => {\n        if (!frame) frame = requestAnimationFrame(update)\n      }\n      const refresh = () => {\n        measure()\n        const v = position()\n        apply(v)\n        toggle(v)\n      }\n      let active = true\n      refresh()\n      setStage(store, { progress: last }, false)\n      el.setAttribute(\"data-ready\", \"\")\n      target.addEventListener(\"scroll\", schedule, { passive: true })\n      window.addEventListener(\"resize\", refresh)\n      const resize = typeof ResizeObserver === \"undefined\" ? null : new ResizeObserver(refresh)\n      resize?.observe(el)\n      document.fonts?.ready.then(() => alive && active && refresh())\n      return () => {\n        active = false\n        target.removeEventListener(\"scroll\", schedule)\n        window.removeEventListener(\"resize\", refresh)\n        resize?.disconnect()\n        if (frame) cancelAnimationFrame(frame)\n        window.clearTimeout(still)\n        el.removeAttribute(\"data-ready\")\n      }\n    }\n\n    let teardown: (() => void) | null = null\n    const start = (layout: StageLayout) => {\n      teardown?.()\n      teardown = setup(layout)\n    }\n    if (forced) {\n      start(forced)\n      return () => {\n        alive = false\n        teardown?.()\n      }\n    }\n    // the layout follows the media queries, as the tracks were measured per layout\n    const media = Object.fromEntries(Object.entries({ ...QUERIES, ...queries }).map(([key, query]) => [key, window.matchMedia?.(query) ?? null])) as Record<\n      StageLayout,\n      MediaQueryList | null\n    >\n    const pick = (): StageLayout => (media.desktop?.matches ? \"desktop\" : media.tablet?.matches ? \"tablet\" : \"phone\")\n    let current = pick()\n    start(current)\n    const onChange = () => {\n      const next = pick()\n      if (next === current) return\n      current = next\n      start(next)\n    }\n    const lists = Object.values(media).filter((m): m is MediaQueryList => !!m)\n    lists.forEach((m) => m.addEventListener?.(\"change\", onChange))\n    return () => {\n      alive = false\n      lists.forEach((m) => m.removeEventListener?.(\"change\", onChange))\n      teardown?.()\n    }\n  }, [tracks, length, queries, mirror, scroller, forced, store])\n\n  return (\n    <StoreContext.Provider value={store}>\n      <div ref={root} data-slot=\"scroll-stage\" className={cn(STAGE, className)} {...props}>\n        {children}\n      </div>\n    </StoreContext.Provider>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "meta": {
    "added": "2026-10-27",
    "unlisted": true
  },
  "categories": [
    "scroll",
    "layout"
  ],
  "type": "registry:ui"
}