{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "scene",
  "title": "Scene",
  "description": "A small picture of a product at work that plays once, a step at a time, when it is seen, and lands on its end under reduced motion. A script plays timed events through a reducer when asked, on the page’s clock, and can stop part-way and wait for the visitor’s decision.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/live.json",
    "https://kinoui.com/r/resize.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/lib/scene.ts",
      "content": "'use client'\n\nimport { afterPageTime, liveNow } from '@/registry/lib/live'\nimport { reducesMotion } from '@/registry/lib/reduce-motion'\nimport { FOLLOWS_TRANSITION, roleDuration } from '@/registry/lib/resize'\nimport {\n  type Dispatch,\n  type RefObject,\n  type SetStateAction,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react'\n\n/*\n * A scene: a small picture of a product at work that plays once, a step at a\n * time, when it is seen, such as a feature's picture on a landing page.\n * Under reduced motion it lands on its last step instead of playing.\n *\n * A script plays when it is asked to instead, such as a preview's reply when\n * the visitor sends a message: timed events folded into a state by a\n * reducer, on the page's clock, that can stop part-way and wait at a step for\n * the visitor's decision.\n */\n\n/** Where a scene is: not seen yet, seen and playing, or landed on its end under reduced motion. */\ntype SceneSeen = 'waiting' | 'seen' | 'reduced'\n\n/** The share of an element that has to be on screen for all of it to be seen, short of a scene taller than the screen. */\nfunction fullView(height: number, viewport: number): number {\n  return Math.min(0.9, (0.9 * viewport) / height)\n}\n\n/**\n * Whether a scene has been seen: `seen` once it is in full view (or fills most\n * of the screen), or once `share` of it is; `reduced` at once under reduced\n * motion, where it lands on its end instead of playing. `landing` holds for\n * the two frames that jump to the end, so nothing fades or slides into it on\n * load (motion rule 6): the scene's frame takes it as `data-landing`.\n */\nfunction useSeen<Element extends HTMLElement>(\n  /** The share of it on screen that starts it; all of it by default. */\n  share?: number,\n): {\n  ref: RefObject<Element | null>\n  seen: SceneSeen\n  landing: boolean\n} {\n  const ref = useRef<Element>(null)\n  const [seen, setSeen] = useState<SceneSeen>('waiting')\n  const [landed, setLanded] = useState(false)\n\n  useEffect(() => {\n    const element = ref.current\n    if (!element) return\n    if (reducesMotion(element)) {\n      setSeen('reduced')\n      return\n    }\n    const observer = new IntersectionObserver(\n      ([entry]) => {\n        if (!entry?.isIntersecting) return\n        observer.disconnect()\n        // Read again now: reduced motion may have been asked for since it mounted.\n        setSeen(reducesMotion(element) ? 'reduced' : 'seen')\n      },\n      { threshold: share ?? fullView(element.offsetHeight, window.innerHeight) },\n    )\n    observer.observe(element)\n    return () => observer.disconnect()\n  }, [share])\n\n  useEffect(() => {\n    if (seen !== 'reduced') return\n    let frame = requestAnimationFrame(() => {\n      frame = requestAnimationFrame(() => setLanded(true))\n    })\n    return () => cancelAnimationFrame(frame)\n  }, [seen])\n\n  return { ref, seen, landing: seen === 'reduced' && !landed }\n}\n\n/** Whether any of `element` is on screen: one that is as the page shows stays as it was painted (motion rule 6). */\nfunction onScreen(element: Element) {\n  const box = element.getBoundingClientRect()\n  return (\n    box.bottom > 0 &&\n    box.top < window.innerHeight &&\n    box.right > 0 &&\n    box.left < window.innerWidth\n  )\n}\n\n/** The `enter` role's duration in the default feel, Crisp, in ms: what a scene's steps are written against. */\nconst CRISP_ENTER_MS = 500\n\n/** How much longer than in Crisp the `enter` role runs where `element` is, so a scene keeps pace with the feel. */\nfunction feelStretch(element: Element): number {\n  const ms = roleDuration(element, 'enter')\n  return ms > 0 ? ms / CRISP_ENTER_MS : 1\n}\n\n/**\n * The step a scene is on, `elapsed` ms after it started: how many of `steps`\n * have landed.\n */\nfunction sceneStep(steps: readonly number[], elapsed: number): number {\n  return steps.filter((at) => at <= elapsed).length\n}\n\n/**\n * Plays a scripted scene once it is seen (`useSeen`): each entry of `steps`\n * is how many ms after the start that step lands in the default feel, Crisp.\n * A slower feel stretches them with its `enter` role, and so does a tool\n * that slows the roles, such as the playground's Speed. Under reduced motion it is on its last step. `replay`\n * starts it over.\n */\nfunction useScene<Element extends HTMLElement>(\n  steps: readonly number[],\n  /** The share of it on screen that starts it; all of it by default. */\n  share?: number,\n): {\n  ref: RefObject<Element | null>\n  step: number\n  done: boolean\n  landing: boolean\n  /** Counts the plays, to start what the scene holds over on a replay. */\n  run: number\n  replay: () => void\n} {\n  const { ref, seen, landing } = useSeen<Element>(share)\n  const [played, setPlayed] = useState(0)\n  const [run, setRun] = useState(0)\n\n  useEffect(() => {\n    const element = ref.current\n    if (seen !== 'seen' || !element || steps.length === 0) return\n    const stretch = feelStretch(element)\n    const clock = element.animate([], {\n      duration: Math.max(...steps) * stretch,\n      id: FOLLOWS_TRANSITION,\n    })\n    let frame = requestAnimationFrame(function tick() {\n      const elapsed = Number(clock.currentTime ?? 0) / stretch\n      const step =\n        clock.playState === 'finished' ? steps.length : sceneStep(steps, elapsed)\n      setPlayed(step)\n      if (step < steps.length) frame = requestAnimationFrame(tick)\n    })\n    return () => {\n      cancelAnimationFrame(frame)\n      clock.cancel()\n    }\n  }, [steps, seen, run, ref])\n\n  const step = seen === 'reduced' ? steps.length : played\n  return {\n    ref,\n    step,\n    done: step === steps.length,\n    landing,\n    run,\n    replay: () => {\n      setPlayed(0)\n      setRun((last) => last + 1)\n    },\n  }\n}\n\n/* Scripts */\n\n/**\n * One step of a script: an event that lands `at` ms after the play started,\n * or after the last wait, on the page's clock; or a wait for the visitor's\n * decision, which is reached as soon as the step before it lands.\n */\ntype ScriptStep<Event> = { at: number; event: Event } | { wait: 'decision' }\n\n/** Where a play is: not playing, playing `steps` from `next`, or held at the wait at `next`. */\ntype ScriptPlay<Event> =\n  | { status: 'idle' }\n  | {\n      status: 'playing'\n      steps: readonly ScriptStep<Event>[]\n      next: number\n      /** When the play started, or the last wait was passed, on the page's clock. */\n      since: number\n    }\n  | { status: 'waiting'; steps: readonly ScriptStep<Event>[]; next: number }\n\n/** A script's state and where its play is. */\ninterface Script<State, Event> {\n  state: State\n  play: ScriptPlay<Event>\n}\n\nconst NOT_PLAYING = Object.freeze({ status: 'idle' }) satisfies ScriptPlay<never>\n\n/** A script at `initial`, not playing: where it starts, and where a reset goes back to. */\nfunction scriptOf<State, Event>(initial: State): Script<State, Event> {\n  return { state: initial, play: NOT_PLAYING }\n}\n\n/** The script playing `steps` from the first, from its state as it is, at `now`. The same script while it plays. */\nfunction scriptPlay<State, Event>(\n  script: Script<State, Event>,\n  steps: readonly ScriptStep<Event>[],\n  now: number,\n): Script<State, Event> {\n  if (script.play.status !== 'idle') return script\n  return { ...script, play: { status: 'playing', steps, next: 0, since: now } }\n}\n\n/** The script held where it is, not playing. */\nfunction scriptStop<State, Event>(script: Script<State, Event>): Script<State, Event> {\n  return script.play.status === 'idle' ? script : { ...script, play: NOT_PLAYING }\n}\n\n/**\n * The script after the visitor's decision: `decision` changes the state, and\n * a play held at a wait plays on past it, its next steps timed from `now`.\n */\nfunction scriptDecide<State, Event>(\n  script: Script<State, Event>,\n  decision: (state: State) => State,\n  now: number,\n): Script<State, Event> {\n  const { play } = script\n  return {\n    state: decision(script.state),\n    play:\n      play.status === 'waiting'\n        ? { status: 'playing', steps: play.steps, next: play.next + 1, since: now }\n        : play,\n  }\n}\n\n/**\n * The script with every step due at `now` landed, in order, through\n * `reducer`: up to a step whose time hasn't come, or a wait, which holds it.\n * With `land`, as under reduced motion, every step up to the next wait lands\n * at once. Past the last step it stops playing. `due` is how long, on the\n * page's clock, until the next step lands, while it plays; the same script\n * when nothing landed.\n */\nfunction scriptLand<State, Event>(\n  script: Script<State, Event>,\n  reducer: (state: State, event: Event) => State,\n  now: number,\n  land: boolean,\n): { script: Script<State, Event>; due: number | null } {\n  const { play } = script\n  if (play.status !== 'playing') return { script, due: null }\n  let { state } = script\n  let next = play.next\n  for (; next < play.steps.length; next++) {\n    const step = play.steps[next]\n    if ('wait' in step) {\n      return {\n        script: { state, play: { status: 'waiting', steps: play.steps, next } },\n        due: null,\n      }\n    }\n    if (!land && step.at > now - play.since) {\n      if (next === play.next) return { script, due: step.at - (now - play.since) }\n      return { script: { state, play: { ...play, next } }, due: null }\n    }\n    state = reducer(state, step.event)\n  }\n  return { script: { state, play: NOT_PLAYING }, due: null }\n}\n\n/**\n * Lands a script's steps on the page's clock while it plays, so the\n * playground's Speed slows it, even when changed part-way: a render when a\n * step lands, never one per frame. Under reduced motion each stretch up to a\n * wait lands at once. Unmounting cancels.\n */\nfunction useScriptClock<State, Event>(\n  script: Script<State, Event>,\n  setScript: Dispatch<SetStateAction<Script<State, Event>>>,\n  reducer: (state: State, event: Event) => State,\n) {\n  useLayoutEffect(() => {\n    if (script.play.status !== 'playing') return undefined\n    let cancel = () => {}\n    const tick = () => {\n      const landed = scriptLand(script, reducer, liveNow(), reducesMotion())\n      // Only onto the script it was worked out from, so an effect run twice lands once.\n      if (landed.script !== script)\n        setScript((current) => (current === script ? landed.script : current))\n      else if (landed.due !== null) cancel = afterPageTime(landed.due, tick)\n    }\n    tick()\n    return () => cancel()\n  }, [script, setScript, reducer])\n}\n\n/**\n * Plays steps through `reducer` from `initial` when asked, on the page's\n * clock. Nothing plays until `play(steps)`, which plays them from the state\n * as it is and does nothing while a play goes on. `stop()` holds where it\n * is and `reset()` goes back to `initial`. `decide(decision)` changes the\n * state with the visitor's decision and plays on past a wait; `change`\n * changes it and leaves the play as it is. Under reduced motion a play lands\n * on its end, or on its next wait, in the commit that starts it.\n */\nfunction useScript<State, Event>(\n  reducer: (state: State, event: Event) => State,\n  initial: State,\n): {\n  state: State\n  /** From `play()` until its last step lands or it stops, waits included. */\n  playing: boolean\n  play: (steps: readonly ScriptStep<Event>[]) => void\n  stop: () => void\n  reset: () => void\n  decide: (decision: (state: State) => State) => void\n  change: (update: (state: State) => State) => void\n} {\n  const [script, setScript] = useState(() => scriptOf<State, Event>(initial))\n  useScriptClock(script, setScript, reducer)\n\n  const act = (\n    action: (script: Script<State, Event>, now: number) => Script<State, Event>,\n  ) => {\n    const now = liveNow()\n    const land = reducesMotion()\n    setScript((current) => scriptLand(action(current, now), reducer, now, land).script)\n  }\n\n  return {\n    state: script.state,\n    playing: script.play.status !== 'idle',\n    play: (steps) => act((current, now) => scriptPlay(current, steps, now)),\n    stop: () => setScript(scriptStop),\n    reset: () => setScript(scriptOf(initial)),\n    decide: (decision) => act((current, now) => scriptDecide(current, decision, now)),\n    change: (update) =>\n      setScript((current) => {\n        const state = update(current.state)\n        return state === current.state ? current : { ...current, state }\n      }),\n  }\n}\n\nexport {\n  type SceneSeen,\n  type Script,\n  type ScriptPlay,\n  type ScriptStep,\n  CRISP_ENTER_MS,\n  feelStretch,\n  fullView,\n  onScreen,\n  scriptDecide,\n  sceneStep,\n  scriptLand,\n  scriptOf,\n  scriptPlay,\n  scriptStop,\n  useScene,\n  useScript,\n  useSeen,\n}\n",
      "type": "registry:lib",
      "target": "@lib/scene.ts"
    }
  ],
  "type": "registry:lib"
}