{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "model-stage",
  "type": "registry:component",
  "title": "Model Stage",
  "description": "A turntable for any mesh or group: centres and fits it, turns it slowly, and lets the pointer orbit it within limits.",
  "categories": [
    "three"
  ],
  "dependencies": [
    "@react-three/fiber",
    "three"
  ],
  "devDependencies": [
    "@types/three"
  ],
  "registryDependencies": [
    "@rivier-ui/theme"
  ],
  "files": [
    {
      "path": "registry/three/model-stage.tsx",
      "type": "registry:component",
      "target": "components/three/model-stage.tsx",
      "content": "\"use client\";\n/**\n * @name model-stage\n * @category three\n * @description A turntable for any mesh or group: centres and fits it, turns it slowly, and lets the pointer orbit it within limits.\n * @when Showing one object: a product, a loaded model, a shape of your own. Use it inside scene. For decoration without a subject use orb or floating-shapes.\n * @example\n * <Scene aspect={4 / 3} label=\"A turning torus knot\">\n *   <ModelStage>\n *     <mesh>\n *       <torusKnotGeometry args={[1, 0.32, 128, 16]} />\n *       <meshStandardMaterial flatShading />\n *     </mesh>\n *   </ModelStage>\n * </Scene>\n */\n/* eslint-disable react-hooks/immutability -- three.js objects (uniforms, the canvas, scene nodes) are changed in place by design, in effects and frames, never during render */\nimport { useFrame, useThree } from \"@react-three/fiber\";\nimport { useEffect, useLayoutEffect, useMemo, useRef, type ReactNode } from \"react\";\nimport { Box3, Vector3, type Group } from \"three\";\n\nexport type ModelStageProps = {\n  /** The mesh or group to show. Load models inside a Suspense boundary that also wraps the stage, so it fits them once they exist. */\n  children?: ReactNode;\n  /** Turn on its own when not being dragged. */\n  autoRotate?: boolean;\n  /** Turning speed in radians per second. */\n  speed?: number;\n  /** Let the pointer orbit it. Horizontal drags turn; vertical touches still scroll the page. */\n  draggable?: boolean;\n  /** How far it can be tipped away from and toward the viewer, in radians: [min, max]. */\n  polar?: [number, number];\n  /** The tip it starts at, in radians. */\n  initialPolar?: number;\n  /** Limits for turning, in radians: [min, max]. Without it the object turns all the way round. */\n  azimuth?: [number, number];\n  /** The largest dimension the object is scaled to, in scene units. `false` keeps its own size and only centres it. */\n  size?: number | false;\n  /** Add an ambient and a directional light. Turn off to light the object yourself. */\n  lights?: boolean;\n  /** Where the stage sits in the scene. */\n  position?: [number, number, number];\n};\n\nconst clamp = (value: number, min: number, max: number): number => Math.max(min, Math.min(max, value));\n\nexport function ModelStage({\n  children,\n  autoRotate = true,\n  speed = 0.4,\n  draggable = true,\n  polar = [-0.3, 0.7],\n  initialPolar = 0.2,\n  azimuth,\n  size = 3,\n  lights = true,\n  position,\n}: ModelStageProps) {\n  const tilt = useRef<Group>(null);\n  const pivot = useRef<Group>(null);\n  const content = useRef<Group>(null);\n  const motion = useRef({ turn: 0, tip: initialPolar, velocity: 0, direction: 1, dragging: false, pointer: -1, x: 0, y: 0, at: 0 });\n  const canvas = useThree((state) => state.gl.domElement);\n  const invalidate = useThree((state) => state.invalidate);\n  const [minPolar, maxPolar] = polar;\n  const minAzimuth = azimuth?.[0] ?? -Infinity;\n  const maxAzimuth = azimuth?.[1] ?? Infinity;\n\n  // Scratch maths objects, made once. They hold no GPU memory, so there is nothing to dispose.\n  const scratch = useMemo(() => ({ box: new Box3(), center: new Vector3(), extent: new Vector3(), scale: new Vector3() }), []);\n\n  // Centre and fit after every render of the stage: the child may have changed.\n  useLayoutEffect(() => {\n    const outer = tilt.current;\n    const turntable = pivot.current;\n    const inner = content.current;\n    if (!outer || !turntable || !inner) return;\n    inner.position.set(0, 0, 0);\n    inner.scale.setScalar(1);\n    // Measure with the stage unturned (the next frame turns it back), in the turntable's own space.\n    outer.rotation.set(0, 0, 0);\n    turntable.rotation.set(0, 0, 0);\n    turntable.updateWorldMatrix(true, true);\n    scratch.box.setFromObject(inner);\n    if (scratch.box.isEmpty()) return;\n    scratch.box.getCenter(scratch.center);\n    scratch.box.getSize(scratch.extent);\n    turntable.worldToLocal(scratch.center);\n    const parentScale = turntable.getWorldScale(scratch.scale).x || 1;\n    const largest = Math.max(scratch.extent.x, scratch.extent.y, scratch.extent.z) / parentScale;\n    const factor = size === false || largest <= 0 ? 1 : size / largest;\n    inner.scale.setScalar(factor);\n    inner.position.copy(scratch.center).multiplyScalar(-factor);\n    invalidate();\n  });\n\n  useEffect(() => {\n    if (!draggable) return;\n    const state = motion.current;\n    const before = { touchAction: canvas.style.touchAction, cursor: canvas.style.cursor };\n    canvas.style.touchAction = \"pan-y\";\n    canvas.style.cursor = \"grab\";\n\n    const down = (event: PointerEvent): void => {\n      if (event.pointerType === \"mouse\" && event.button !== 0) return;\n      state.dragging = true;\n      state.pointer = event.pointerId;\n      state.x = event.clientX;\n      state.y = event.clientY;\n      state.at = event.timeStamp;\n      state.velocity = 0;\n      canvas.setPointerCapture(event.pointerId);\n      canvas.style.cursor = \"grabbing\";\n    };\n    const move = (event: PointerEvent): void => {\n      if (!state.dragging || event.pointerId !== state.pointer) return;\n      const turn = (event.clientX - state.x) * 0.008;\n      const seconds = Math.max(1, event.timeStamp - state.at) / 1000;\n      state.turn = clamp(state.turn + turn, minAzimuth, maxAzimuth);\n      state.tip = clamp(state.tip + (event.clientY - state.y) * 0.006, minPolar, maxPolar);\n      state.velocity = state.velocity * 0.6 + (turn / seconds) * 0.4;\n      state.x = event.clientX;\n      state.y = event.clientY;\n      state.at = event.timeStamp;\n      invalidate();\n    };\n    const up = (event: PointerEvent): void => {\n      if (event.pointerId !== state.pointer) return;\n      state.dragging = false;\n      state.pointer = -1;\n      // Held still before letting go: no throw.\n      if (event.timeStamp - state.at > 100) state.velocity = 0;\n      state.velocity = clamp(state.velocity, -8, 8);\n      if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);\n      canvas.style.cursor = \"grab\";\n    };\n\n    canvas.addEventListener(\"pointerdown\", down);\n    canvas.addEventListener(\"pointermove\", move);\n    canvas.addEventListener(\"pointerup\", up);\n    canvas.addEventListener(\"pointercancel\", up);\n    return () => {\n      canvas.removeEventListener(\"pointerdown\", down);\n      canvas.removeEventListener(\"pointermove\", move);\n      canvas.removeEventListener(\"pointerup\", up);\n      canvas.removeEventListener(\"pointercancel\", up);\n      canvas.style.touchAction = before.touchAction;\n      canvas.style.cursor = before.cursor;\n      state.dragging = false;\n    };\n  }, [canvas, draggable, invalidate, minAzimuth, maxAzimuth, minPolar, maxPolar]);\n\n  useFrame((_, delta) => {\n    const dt = Math.min(delta, 0.1);\n    const state = motion.current;\n    if (!state.dragging) {\n      const own = autoRotate ? speed * state.direction : 0;\n      state.turn += (own + state.velocity) * dt;\n      state.velocity *= Math.exp(-dt * 3);\n      // With limits, the turntable swings back and forth between them.\n      if (state.turn > maxAzimuth) {\n        state.turn = maxAzimuth;\n        state.direction = -1;\n        state.velocity = 0;\n      } else if (state.turn < minAzimuth) {\n        state.turn = minAzimuth;\n        state.direction = 1;\n        state.velocity = 0;\n      }\n    }\n    state.tip = clamp(state.tip, minPolar, maxPolar);\n    if (tilt.current) tilt.current.rotation.x = state.tip;\n    if (pivot.current) pivot.current.rotation.y = state.turn;\n  });\n\n  return (\n    <>\n      {lights ? (\n        <>\n          <ambientLight intensity={1.9} />\n          <directionalLight position={[3, 5, 4]} intensity={1.7} />\n        </>\n      ) : null}\n      <group ref={tilt} position={position}>\n        <group ref={pivot}>\n          <group ref={content}>{children}</group>\n        </group>\n      </group>\n    </>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "three",
    "when": "Showing one object: a product, a loaded model, a shape of your own. Use it inside scene. For decoration without a subject use orb or floating-shapes.",
    "example": "<Scene aspect={4 / 3} label=\"A turning torus knot\">\n  <ModelStage>\n    <mesh>\n      <torusKnotGeometry args={[1, 0.32, 128, 16]} />\n      <meshStandardMaterial flatShading />\n    </mesh>\n  </ModelStage>\n</Scene>",
    "client": true
  }
}
