{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "model-viewer",
  "type": "registry:component",
  "title": "Model Viewer",
  "description": "Shows one 3D model that a person can turn, zoom and reset: a glTF or GLB file, or Gaussian splats (.spz, .ply, .splat, .ksplat, .sog), with a poster and progress while it loads and a still fallback where 3D cannot run.",
  "categories": [
    "three"
  ],
  "dependencies": [
    "@sparkjsdev/spark",
    "lucide-react",
    "three"
  ],
  "devDependencies": [
    "@types/three"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/announce",
    "@rivier-ui/cn",
    "@rivier-ui/progress",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/three/model-viewer.tsx",
      "type": "registry:component",
      "target": "components/three/model-viewer.tsx",
      "content": "\"use client\";\n/**\n * @name model-viewer\n * @category three\n * @description Shows one 3D model that a person can turn, zoom and reset: a glTF or GLB file, or Gaussian splats (.spz, .ply, .splat, .ksplat, .sog), with a poster and progress while it loads and a still fallback where 3D cannot run.\n * @when A file to look at from every side: an object, a product, a scanned place. It is a whole viewer, not a part of scene: for your own meshes inside a react-three-fiber canvas use scene with model-stage. Nothing heavy is in this file: three.js is fetched when the viewer comes near the screen, its glTF loader only for glTF, and Spark (`@sparkjsdev/spark`, installed with this item) only when the file is splats. glTF that carries splats in an extension is not read (Spark has no glTF loader); Draco, Meshopt and KTX2 compression need their decoders set in `configureLoader`. Plain wheel and vertical swipes scroll the page: zoom is pinch, Ctrl with the wheel, the keys or the buttons. To compare two models, give two viewers the same `view` and `bounds` inside compare-slider, with `children={null}` and buttons of your own that change the shared view.\n * @example\n * <ModelViewer src=\"/models/vase.glb\" alt=\"A clay vase with a painted belt\" poster=\"/models/vase.jpg\" />\n *\n * // Splats, turning by itself (never under reduced motion), with a hand-off to AR on phones\n * <ModelViewer\n *   src=\"/models/courtyard.spz\"\n *   alt=\"The courtyard, scanned in 2026\"\n *   autoRotate\n *   rotation={[180, 0, 0]}\n *   ar={{ usdz: \"/models/courtyard.usdz\", glb: \"https://example.com/models/courtyard.glb\" }}\n * />\n *\n * // Two viewers, one camera\n * const [view, setView] = useState<ModelView>({ azimuth: 0, polar: 15, zoom: 1 });\n * const frame = { center: [0, 4, 0], radius: 9 } as const; // one sphere for both, so they keep their sizes and line up\n * <ModelViewer src=\"/models/then.glb\" alt=\"As built\" view={view} onViewChange={setView} bounds={frame} />\n * <ModelViewer src=\"/models/now.glb\" alt=\"Today\" view={view} onViewChange={setView} bounds={frame} />\n */\nimport { ArrowLeft, ArrowRight, Box, Minus, Pause, Play, Plus, RotateCcw } from \"lucide-react\";\nimport {\n  createContext,\n  use,\n  useEffect,\n  useId,\n  useImperativeHandle,\n  useRef,\n  useState,\n  useSyncExternalStore,\n  type ComponentProps,\n  type KeyboardEvent,\n  type PointerEvent,\n  type ReactNode,\n  type Ref,\n} from \"react\";\nimport type { Object3D } from \"three\";\nimport type { GLTFLoader } from \"three/examples/jsm/loaders/GLTFLoader.js\";\nimport { Progress } from \"@/components/ui/progress\";\nimport { announce } from \"@/lib/announce\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\n\n/** Where the model is seen from. Plain numbers, so two viewers can share one. */\nexport type ModelView = {\n  /** How far the model is turned to the right, in degrees (-180 to 180). 0 is its front. */\n  azimuth: number;\n  /** How far above its middle it is seen from, in degrees. 0 is level; 90 looks straight down. */\n  polar: number;\n  /** 1 fits the whole model in the frame; 2 is twice as close. */\n  zoom: number;\n};\n\n/** A sphere in the file's own units (after `rotation`): what the viewer fits to its frame. */\nexport type ModelBounds = { center: readonly [number, number, number]; radius: number };\n\nexport type ModelKind = \"gltf\" | \"splat\";\nexport type ModelViewerStatus = \"idle\" | \"loading\" | \"ready\" | \"error\" | \"unsupported\";\n\nexport type ModelViewerLabels = {\n  /** What kind of thing the viewer is, said after its name (\"3D model\"). */\n  roledescription: string;\n  /** How to use it from the keyboard, read after its name. */\n  instructions: string;\n  /** The name of the group of buttons. */\n  controls: string;\n  turnLeft: string;\n  turnRight: string;\n  zoomIn: string;\n  zoomOut: string;\n  reset: string;\n  stopTurning: string;\n  startTurning: string;\n  /** The name of the progress bar. */\n  loading: string;\n  /** Shown when the file cannot be fetched or read. */\n  failed: string;\n  /** Shown when the browser has no WebGL 2. */\n  unsupported: string;\n  /** The button that opens the model in the phone's AR viewer. */\n  ar: string;\n  /** What is announced after a key or a button changes the view. Return \"\" to say nothing. */\n  view: (view: ModelView, locale: string | undefined) => string;\n};\n\nconst describeView = (view: ModelView, locale: string | undefined): string => {\n  const degrees = new Intl.NumberFormat(locale, { style: \"unit\", unit: \"degree\", unitDisplay: \"long\", maximumFractionDigits: 0 });\n  const percent = new Intl.NumberFormat(locale, { style: \"percent\", maximumFractionDigits: 0 });\n  const turn = view.azimuth === 0 ? \"Front\" : `Turned ${degrees.format(Math.abs(view.azimuth))} to the ${view.azimuth > 0 ? \"right\" : \"left\"}`;\n  const height = view.polar === 0 ? \"level\" : `from ${degrees.format(Math.abs(view.polar))} ${view.polar > 0 ? \"above\" : \"below\"}`;\n  return `${turn}, ${height}, zoom ${percent.format(view.zoom)}`;\n};\n\nconst DEFAULT_LABELS: ModelViewerLabels = {\n  roledescription: \"3D model\",\n  instructions: \"Arrow keys turn the model, plus and minus zoom, Home resets the view.\",\n  controls: \"View\",\n  turnLeft: \"Turn left\",\n  turnRight: \"Turn right\",\n  zoomIn: \"Zoom in\",\n  zoomOut: \"Zoom out\",\n  reset: \"Reset the view\",\n  stopTurning: \"Stop turning\",\n  startTurning: \"Start turning\",\n  loading: \"Loading the 3D model\",\n  failed: \"The 3D model could not be loaded.\",\n  unsupported: \"This browser cannot show 3D here.\",\n  ar: \"View in your space\",\n  view: describeView,\n};\n\n/** What the phone's own AR viewer is given. Each is used only on the platform that reads it. */\nexport type ModelViewerAr = {\n  /** A USDZ file, for AR Quick Look on iPhone and iPad. */\n  usdz?: string;\n  /** A GLB file at an absolute https address, for Scene Viewer on Android. Left out, `src` is used when it is glTF. */\n  glb?: string;\n  /** The name Scene Viewer shows. */\n  title?: string;\n};\n\nexport type ModelViewerHandle = {\n  /** Back to the starting view. */\n  reset: () => void;\n  /** Draws a frame and returns it as a PNG data address (for a poster), or null before the model is ready. */\n  snapshot: () => string | null;\n};\n\nconst SPLAT_FILE = /\\.(spz|ply|splat|ksplat|sog)(?:[?#]|$)/i;\n\n/** What a file is, from its name: splats for .spz, .ply, .splat, .ksplat and .sog, glTF for everything else. */\nexport function modelKindOf(src: string): ModelKind {\n  return SPLAT_FILE.test(src) ? \"splat\" : \"gltf\";\n}\n\nconst DEFAULT_VIEW: ModelView = { azimuth: 0, polar: 15, zoom: 1 };\nconst TURN_STEP = 15;\nconst TILT_STEP = 10;\nconst ZOOM_STEP = 1.25;\n/** The camera's vertical field of view, in degrees. */\nconst FIELD = 35;\n\nconst clamp = (value: number, min: number, max: number): number => Math.max(min, Math.min(max, value));\n/** Any angle as the same direction between -180 (not included) and 180. */\nconst wrap = (degrees: number): number => {\n  const turned = (((degrees + 180) % 360) + 360) % 360;\n  return turned === 0 ? 180 : turned - 180;\n};\n\n// ---- What the browser can do, read without an effect so nothing is set during one.\n\nconst never = (): (() => void) => () => {};\nlet webgl2: boolean | undefined;\n\nfunction hasWebGL2(): boolean {\n  if (webgl2 !== undefined) return webgl2;\n  try {\n    const context = document.createElement(\"canvas\").getContext(\"webgl2\");\n    webgl2 = context !== null;\n    // Give the probe's context back at once: browsers allow only a few.\n    context?.getExtension(\"WEBGL_lose_context\")?.loseContext();\n  } catch {\n    webgl2 = false;\n  }\n  return webgl2;\n}\n\nconst REDUCED = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void): (() => void) => {\n  const query = window.matchMedia(REDUCED);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\nconst subscribeTab = (onChange: () => void): (() => void) => {\n  document.addEventListener(\"visibilitychange\", onChange);\n  return () => document.removeEventListener(\"visibilitychange\", onChange);\n};\n\ntype ArPlatform = \"quicklook\" | \"sceneviewer\" | \"none\";\nlet arPlatform: ArPlatform | undefined;\n\n/** AR Quick Look is announced by the browser itself (`rel=\"ar\"`); Scene Viewer is an Android app reached by an intent address. */\nfunction readArPlatform(): ArPlatform {\n  if (arPlatform !== undefined) return arPlatform;\n  if (document.createElement(\"a\").relList.supports(\"ar\")) arPlatform = \"quicklook\";\n  else if (/android/i.test(navigator.userAgent)) arPlatform = \"sceneviewer\";\n  else arPlatform = \"none\";\n  return arPlatform;\n}\n\n// ---- The engine: plain three.js, made after the heavy code has been fetched. Nothing here runs on the server.\n\ntype Engine = {\n  /** The sphere that was fitted to the frame. */\n  bounds: ModelBounds;\n  setView: (view: ModelView) => void;\n  /** Stops drawing while the viewer is off screen or the tab is hidden. */\n  setActive: (active: boolean) => void;\n  snapshot: () => string;\n  dispose: () => void;\n};\n\ntype EngineOptions = {\n  host: HTMLElement;\n  src: string;\n  kind: ModelKind;\n  rotation: readonly [number, number, number];\n  bounds: ModelBounds | undefined;\n  view: ModelView;\n  active: boolean;\n  onProgress: (fraction: number | null) => void;\n  onLost: () => void;\n  configureLoader: ((loader: GLTFLoader) => void) | undefined;\n  /** Set when the viewer went away while the engine was still loading. */\n  signal: { cancelled: boolean };\n};\n\nconst fraction = (event: ProgressEvent): number | null => (event.lengthComputable && event.total > 0 ? Math.min(1, event.loaded / event.total) : null);\n\nasync function createEngine({ host, src, kind, rotation, bounds: given, view, active, onProgress, onLost, configureLoader, signal }: EngineOptions): Promise<Engine> {\n  const THREE = await import(\"three\");\n  const cleanup: (() => void)[] = [];\n  const dispose = (): void => {\n    for (const step of cleanup.splice(0).reverse()) step();\n  };\n  const alive = (): void => {\n    if (signal.cancelled) throw new Error(\"The viewer was removed while its model was loading.\");\n  };\n\n  try {\n    alive();\n    // Its own canvas, made here: a canvas keeps one context for life, so a viewer that is set up twice\n    // (a file change, a development re-mount) must not be handed a context that was already given back.\n    const canvas = document.createElement(\"canvas\");\n    canvas.setAttribute(\"aria-hidden\", \"true\");\n    canvas.style.cssText = \"display:block;width:100%;height:100%\";\n    // Splats gain nothing from multisampling and draw much slower with it.\n    const renderer = new THREE.WebGLRenderer({ canvas, alpha: true, antialias: kind === \"gltf\", powerPreference: \"high-performance\" });\n    renderer.setPixelRatio(Math.min(2, window.devicePixelRatio || 1));\n    host.append(canvas);\n    cleanup.push(() => {\n      canvas.removeEventListener(\"webglcontextlost\", onLost);\n      renderer.dispose();\n      renderer.forceContextLoss();\n      canvas.remove();\n    });\n    canvas.addEventListener(\"webglcontextlost\", onLost);\n\n    const scene = new THREE.Scene();\n    const camera = new THREE.PerspectiveCamera(FIELD, 1, 0.05, 100);\n    /** Scales and centres the model; the group inside it carries the `rotation` the project asked for. */\n    const fit = new THREE.Group();\n    const turned = new THREE.Group();\n    turned.rotation.set(...(rotation.map((degrees) => (degrees * Math.PI) / 180) as [number, number, number]));\n    fit.add(turned);\n    scene.add(fit);\n\n    let frame = 0;\n    let running = active;\n    let gone = false;\n    const draw = (): void => {\n      frame = 0;\n      if (!gone && running) renderer.render(scene, camera);\n    };\n    const invalidate = (): void => {\n      if (frame === 0 && running && !gone) frame = requestAnimationFrame(draw);\n    };\n    cleanup.push(() => {\n      gone = true;\n      cancelAnimationFrame(frame);\n    });\n\n    const bounds = new THREE.Box3();\n    if (kind === \"gltf\") {\n      const [{ GLTFLoader: Loader }, { RoomEnvironment }] = await Promise.all([import(\"three/examples/jsm/loaders/GLTFLoader.js\"), import(\"three/examples/jsm/environments/RoomEnvironment.js\")]);\n      alive();\n      const loader = new Loader();\n      configureLoader?.(loader);\n      const model = await new Promise<Object3D>((resolve, reject) => {\n        loader.load(\n          src,\n          (gltf) => resolve(gltf.scene),\n          (event) => onProgress(fraction(event)),\n          (error) => reject(error instanceof Error ? error : new Error(`Could not load ${src}`)),\n        );\n      });\n      cleanup.push(() => {\n        model.traverse((node) => {\n          const mesh = node as Partial<{ geometry: { dispose: () => void }; material: unknown }>;\n          mesh.geometry?.dispose();\n          for (const material of Array.isArray(mesh.material) ? mesh.material : mesh.material ? [mesh.material] : []) {\n            for (const value of Object.values(material as Record<string, unknown>)) {\n              if (value instanceof THREE.Texture) value.dispose();\n            }\n            (material as { dispose: () => void }).dispose();\n          }\n        });\n      });\n      alive();\n      // An even, neutral room to be lit by: materials look as their author meant without any lights to place.\n      const room = new RoomEnvironment();\n      const prefilter = new THREE.PMREMGenerator(renderer);\n      const light = prefilter.fromScene(room, 0.04);\n      scene.environment = light.texture;\n      renderer.toneMapping = THREE.NeutralToneMapping;\n      room.dispose();\n      prefilter.dispose();\n      cleanup.push(() => light.dispose());\n      turned.add(model);\n      turned.updateMatrixWorld(true);\n      bounds.setFromObject(turned);\n    } else {\n      const { SparkRenderer, SplatMesh } = await import(\"@sparkjsdev/spark\");\n      alive();\n      // Spark sorts the splats off the main thread and says when a new order is ready to be drawn.\n      const spark = new SparkRenderer({ renderer, onDirty: invalidate });\n      scene.add(spark);\n      const splats = new SplatMesh({ url: src, onProgress: (event) => onProgress(fraction(event)) });\n      cleanup.push(() => {\n        splats.dispose();\n        spark.dispose();\n      });\n      await splats.initialized;\n      alive();\n      turned.add(splats);\n      turned.updateMatrixWorld(true);\n      bounds.copy(splats.getBoundingBox()).applyMatrix4(turned.matrixWorld);\n    }\n    if (bounds.isEmpty()) throw new Error(`${src} holds nothing to show.`);\n\n    // Fit: the model's bounding sphere (or the one the project gave) becomes a sphere of radius 1 at the centre of the scene.\n    const sphere = given ? new THREE.Sphere(new THREE.Vector3(...given.center), given.radius) : bounds.getBoundingSphere(new THREE.Sphere());\n    const scale = sphere.radius > 0 ? 1 / sphere.radius : 1;\n    fit.scale.setScalar(scale);\n    fit.position.copy(sphere.center).multiplyScalar(-scale);\n\n    let current = view;\n    const place = (): void => {\n      // The distance at which that sphere just fits the narrower of the frame's two angles of view.\n      const vertical = (FIELD * Math.PI) / 180;\n      const horizontal = 2 * Math.atan(Math.tan(vertical / 2) * camera.aspect);\n      const distance = (1.05 / Math.sin(Math.min(vertical, horizontal) / 2)) / current.zoom;\n      // Turning the model to the right is the camera going round it to the left.\n      const around = (-current.azimuth * Math.PI) / 180;\n      const above = (current.polar * Math.PI) / 180;\n      camera.position.set(Math.sin(around) * Math.cos(above) * distance, Math.sin(above) * distance, Math.cos(around) * Math.cos(above) * distance);\n      camera.lookAt(0, 0, 0);\n      invalidate();\n    };\n    const resize = (): void => {\n      const width = Math.max(1, host.clientWidth);\n      const height = Math.max(1, host.clientHeight);\n      renderer.setSize(width, height, false);\n      camera.aspect = width / height;\n      camera.updateProjectionMatrix();\n      place();\n    };\n    const observer = new ResizeObserver(resize);\n    observer.observe(host);\n    cleanup.push(() => observer.disconnect());\n    resize();\n    // The first frame is drawn before the viewer says it is ready, so the poster is never swapped for nothing.\n    renderer.render(scene, camera);\n\n    return {\n      bounds: { center: [sphere.center.x, sphere.center.y, sphere.center.z], radius: sphere.radius },\n      setView(next) {\n        current = next;\n        place();\n      },\n      setActive(next) {\n        running = next;\n        if (next) invalidate();\n      },\n      snapshot() {\n        renderer.render(scene, camera);\n        return canvas.toDataURL(\"image/png\");\n      },\n      dispose,\n    };\n  } catch (error) {\n    dispose();\n    throw error;\n  }\n}\n\n// ---- The component.\n\ntype ModelViewerContextValue = {\n  status: ModelViewerStatus;\n  /** 0 to 1 while loading, or null when the amount is not known. */\n  progress: number | null;\n  view: ModelView;\n  labels: ModelViewerLabels;\n  /** Changes the view by a step, announces it, and stops the turning. */\n  act: (change: (view: ModelView) => ModelView) => void;\n  reset: () => void;\n  autoRotate: boolean;\n  turning: boolean;\n  setTurning: (turning: boolean) => void;\n  src: string;\n  kind: ModelKind;\n  ar: ModelViewerAr | undefined;\n  poster: ReactNode;\n};\n\nconst ModelViewerContext = createContext<ModelViewerContextValue | null>(null);\n\nfunction useModelViewer(part: string): ModelViewerContextValue {\n  const context = use(ModelViewerContext);\n  if (!context) throw new Error(`<${part}> must be used inside <ModelViewer>.`);\n  return context;\n}\n\nexport type ModelViewerProps = Omit<ComponentProps<\"div\">, \"children\" | \"onLoad\" | \"onError\"> & {\n  /** The address of the file. */\n  src: string;\n  /** What the file holds. Left out, it is read from the file's name. */\n  format?: ModelKind;\n  /** What the model is, in words: its name for assistive technology, and what stands for it where 3D cannot run. */\n  alt: string;\n  /** A still shown until the model has drawn, and instead of it when it cannot: an address, or an element that fills the frame. */\n  poster?: string | ReactNode;\n  /** The view: controlled. Give two viewers the same one to share a camera. */\n  view?: ModelView;\n  /** The starting view when uncontrolled, and where Home and the reset button return to. */\n  defaultView?: ModelView;\n  onViewChange?: (view: ModelView) => void;\n  /** Turn by itself until the person touches it. Never under reduced motion; a button stops and starts it. */\n  autoRotate?: boolean;\n  /** Degrees per second when turning by itself. */\n  rotateSpeed?: number;\n  /** Turns the model before it is fitted, in degrees about x, y and z: splats trained with y pointing down need [180, 0, 0]. */\n  rotation?: readonly [number, number, number];\n  /** The sphere that is fitted to the frame, in the file's own units. Left out, it is the model's own. Give two viewers the same one so that two files of the same thing keep their sizes and line up (`onLoad` reports each file's own). */\n  bounds?: ModelBounds;\n  /** The lowest and highest the model can be seen from, in degrees. */\n  polarRange?: readonly [number, number];\n  /** The furthest and nearest zoom. */\n  zoomRange?: readonly [number, number];\n  /** Width / height, as a number (4 / 3) or a CSS ratio (\"16 / 9\"). \"auto\" fills the parent's height. */\n  aspect?: number | string;\n  /** Offer the phone's own AR viewer, where there is one: AR Quick Look (needs `usdz`) or Scene Viewer. */\n  ar?: ModelViewerAr;\n  /** Shown instead of the message when the model failed or 3D cannot run: a link to the file, a longer description. */\n  fallback?: ReactNode;\n  /** Sets up the glTF loader before it is used: decoders for Draco, Meshopt or KTX2, a path, headers. */\n  configureLoader?: (loader: GLTFLoader) => void;\n  /** Called once the model has drawn, with the sphere that was fitted to the frame. */\n  onLoad?: (model: { bounds: ModelBounds }) => void;\n  onError?: (error: unknown) => void;\n  /** How far outside the viewport loading starts (an IntersectionObserver margin). */\n  margin?: string;\n  /** The language tag numbers are formatted for in announcements. */\n  locale?: string;\n  labels?: Partial<ModelViewerLabels>;\n  /** `reset()` and `snapshot()`. */\n  handleRef?: Ref<ModelViewerHandle>;\n  /** What sits over the frame. Default: ModelViewerControls, and ModelViewerAr when `ar` is given. Pass null for none. */\n  children?: ReactNode;\n};\n\n/**\n * The frame holds its shape from the first paint (`aspect`), shows the poster, and fetches the 3D code and\n * the file only when it comes near the screen. Once the model has drawn, the surface is one Tab stop: Left\n * and Right turn the model (the same way in every language: it is a picture of an object, not a line of\n * text), Up and Down raise and lower the viewpoint, plus and minus zoom, Home resets. Each key press is\n * announced. A drag turns it; a vertical swipe scrolls the page; pinch, or Ctrl with the wheel, zooms. The\n * buttons do all of it without dragging. Drawing stops while the viewer is off screen or the tab is hidden.\n */\nexport function ModelViewer({\n  className,\n  style,\n  src,\n  format,\n  alt,\n  poster,\n  view: viewProp,\n  defaultView = DEFAULT_VIEW,\n  onViewChange,\n  autoRotate = false,\n  rotateSpeed = 20,\n  rotation,\n  bounds,\n  polarRange,\n  zoomRange,\n  aspect = \"4 / 3\",\n  ar,\n  fallback,\n  configureLoader,\n  onLoad,\n  onError,\n  margin = \"200px\",\n  locale,\n  labels: labelsProp,\n  handleRef,\n  children,\n  ...props\n}: ModelViewerProps) {\n  const labels = { ...DEFAULT_LABELS, ...labelsProp };\n  const kind = format ?? modelKindOf(src);\n  const [minPolar, maxPolar] = polarRange ?? [-60, 85];\n  const [minZoom, maxZoom] = zoomRange ?? [0.5, 4];\n  const [rx, ry, rz] = rotation ?? [0, 0, 0];\n  const instructions = useId();\n\n  const supported = useSyncExternalStore(never, hasWebGL2, () => true);\n  const reduced = useSyncExternalStore(\n    subscribeReduced,\n    () => window.matchMedia(REDUCED).matches,\n    () => false,\n  );\n  const tabVisible = useSyncExternalStore(\n    subscribeTab,\n    () => document.visibilityState !== \"hidden\",\n    () => true,\n  );\n\n  const [root, setRoot] = useState<HTMLDivElement | null>(null);\n  const [host, setHost] = useState<HTMLDivElement | null>(null);\n  const [near, setNear] = useState(false);\n  const [seen, setSeen] = useState(false);\n  const [turning, setTurning] = useState(true);\n  /** What the engine last said about a file. Compared by key, so a new file is \"loading\" at once. */\n  const [loaded, setLoaded] = useState<{ key: string; state: \"ready\" | \"error\" } | null>(null);\n  const [amount, setAmount] = useState<{ key: string; value: number | null } | null>(null);\n  const [view, setViewState] = useControllableState<ModelView>({ value: viewProp, defaultValue: defaultView, onChange: onViewChange });\n\n  const [bx, by, bz] = bounds?.center ?? [0, 0, 0];\n  const radius = bounds?.radius ?? 0;\n  const key = `${kind}\\n${src}\\n${rx},${ry},${rz}\\n${bx},${by},${bz},${radius}`;\n  const status: ModelViewerStatus = !supported ? \"unsupported\" : !seen ? \"idle\" : loaded?.key === key ? loaded.state : \"loading\";\n  const ready = status === \"ready\";\n  const progress = status === \"loading\" && amount?.key === key ? amount.value : null;\n  const drawing = near && tabVisible;\n  const spinning = autoRotate && turning && !reduced && ready && drawing;\n\n  const limit = (next: ModelView): ModelView => ({ azimuth: wrap(next.azimuth), polar: clamp(next.polar, minPolar, maxPolar), zoom: clamp(next.zoom, minZoom, maxZoom) });\n  const setView = (next: ModelView): void => {\n    const limited = limit(next);\n    if (limited.azimuth === view.azimuth && limited.polar === view.polar && limited.zoom === view.zoom) return;\n    setViewState(limited);\n  };\n  const act = (change: (current: ModelView) => ModelView): void => {\n    const next = limit(change(view));\n    setTurning(false);\n    setView(next);\n    const message = labels.view(next, locale);\n    if (message) announce(message);\n  };\n  const reset = (): void => act(() => defaultView);\n\n  const engine = useRef<Engine | null>(null);\n  /** What effects and frames read: the newest props and state, without being set up again for each change. */\n  const latest = useRef({ view, setView, drawing, configureLoader, onLoad, onError });\n  useEffect(() => {\n    latest.current = { view, setView, drawing, configureLoader, onLoad, onError };\n  });\n\n  useImperativeHandle(handleRef, () => ({ reset: () => latest.current.setView(defaultView), snapshot: () => engine.current?.snapshot() ?? null }), [defaultView]);\n\n  useEffect(() => {\n    if (!root) return;\n    // Without IntersectionObserver the viewer cannot know where it is, so it counts as in view.\n    if (typeof IntersectionObserver === \"undefined\") {\n      const frame = requestAnimationFrame(() => {\n        setNear(true);\n        setSeen(true);\n      });\n      return () => cancelAnimationFrame(frame);\n    }\n    const observer = new IntersectionObserver(\n      (entries) => {\n        const inside = entries.some((entry) => entry.isIntersecting);\n        setNear(inside);\n        if (inside) setSeen(true);\n      },\n      { rootMargin: margin },\n    );\n    observer.observe(root);\n    return () => observer.disconnect();\n  }, [root, margin]);\n\n  useEffect(() => {\n    if (!host || !seen || !supported) return;\n    const signal = { cancelled: false };\n    let made: Engine | null = null;\n    createEngine({\n      host,\n      src,\n      kind,\n      rotation: [rx, ry, rz],\n      bounds: radius > 0 ? { center: [bx, by, bz], radius } : undefined,\n      view: latest.current.view,\n      active: latest.current.drawing,\n      onProgress: (value) => setAmount({ key, value }),\n      onLost: () => setLoaded({ key, state: \"error\" }),\n      configureLoader: (loader) => latest.current.configureLoader?.(loader),\n      signal,\n    }).then(\n      (next) => {\n        if (signal.cancelled) {\n          next.dispose();\n          return;\n        }\n        made = next;\n        engine.current = next;\n        next.setView(latest.current.view);\n        next.setActive(latest.current.drawing);\n        setLoaded({ key, state: \"ready\" });\n        latest.current.onLoad?.({ bounds: next.bounds });\n      },\n      (error: unknown) => {\n        if (signal.cancelled) return;\n        setLoaded({ key, state: \"error\" });\n        latest.current.onError?.(error);\n      },\n    );\n    return () => {\n      signal.cancelled = true;\n      if (engine.current === made) engine.current = null;\n      made?.dispose();\n    };\n  }, [host, seen, supported, src, kind, rx, ry, rz, bx, by, bz, radius, key]);\n\n  useEffect(() => {\n    if (ready) engine.current?.setView(view);\n  }, [view, ready]);\n\n  useEffect(() => {\n    if (ready) engine.current?.setActive(drawing);\n  }, [drawing, ready]);\n\n  useEffect(() => {\n    if (!spinning) return;\n    let frame = 0;\n    let before = performance.now();\n    const tick = (now: number): void => {\n      const seconds = Math.min(0.1, (now - before) / 1000);\n      before = now;\n      const current = latest.current;\n      current.setView({ ...current.view, azimuth: current.view.azimuth + rotateSpeed * seconds });\n      frame = requestAnimationFrame(tick);\n    };\n    frame = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(frame);\n  }, [spinning, rotateSpeed]);\n\n  // Ctrl with the wheel (which is also what a trackpad pinch sends) zooms; a plain wheel scrolls the page.\n  // Registered by hand: React's wheel listener is passive and could not stop the browser's own zoom.\n  useEffect(() => {\n    if (!host || !ready) return;\n    const wheel = (event: WheelEvent): void => {\n      if (!event.ctrlKey) return;\n      event.preventDefault();\n      const current = latest.current;\n      current.setView({ ...current.view, zoom: current.view.zoom * Math.exp(-event.deltaY * 0.01) });\n    };\n    host.addEventListener(\"wheel\", wheel, { passive: false });\n    return () => host.removeEventListener(\"wheel\", wheel);\n  }, [host, ready]);\n\n  /** The fingers or the mouse button now down on the surface, and where the drag or the pinch began. */\n  const pointers = useRef<{ at: Map<number, { x: number; y: number }>; from: { x: number; y: number; spread: number; view: ModelView } | null }>({ at: new Map(), from: null });\n  /** Starts measuring again from where the pointers are now: a second finger came down, or one was lifted. */\n  const mark = (): void => {\n    const [first, second] = [...pointers.current.at.values()];\n    pointers.current.from = first ? { x: first.x, y: first.y, spread: second ? Math.hypot(first.x - second.x, first.y - second.y) : 0, view: latest.current.view } : null;\n  };\n  const handlePointerDown = (event: PointerEvent<HTMLDivElement>): void => {\n    if (!ready || (event.pointerType === \"mouse\" && event.button !== 0)) return;\n    event.currentTarget.setPointerCapture(event.pointerId);\n    pointers.current.at.set(event.pointerId, { x: event.clientX, y: event.clientY });\n    mark();\n    setTurning(false);\n  };\n  const handlePointerMove = (event: PointerEvent<HTMLDivElement>): void => {\n    const state = pointers.current;\n    if (!state.at.has(event.pointerId) || !state.from) return;\n    state.at.set(event.pointerId, { x: event.clientX, y: event.clientY });\n    const [first, second] = [...state.at.values()];\n    if (!first) return;\n    // Measured from where the gesture began, so no movement is lost between two renders.\n    const from = state.from;\n    if (second) {\n      const spread = Math.hypot(first.x - second.x, first.y - second.y);\n      if (from.spread > 0 && spread > 0) setView({ ...from.view, zoom: from.view.zoom * (spread / from.spread) });\n      return;\n    }\n    // The surface follows the hand: dragging right turns the model right, dragging down shows it from above.\n    setView({ ...from.view, azimuth: from.view.azimuth + (first.x - from.x) * 0.4, polar: from.view.polar + (first.y - from.y) * 0.3 });\n  };\n  const handlePointerEnd = (event: PointerEvent<HTMLDivElement>): void => {\n    pointers.current.at.delete(event.pointerId);\n    mark();\n    if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);\n  };\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {\n    if (!ready || event.altKey || event.ctrlKey || event.metaKey) return;\n    const changes: Record<string, ((current: ModelView) => ModelView) | undefined> = {\n      ArrowRight: (current) => ({ ...current, azimuth: current.azimuth + TURN_STEP }),\n      ArrowLeft: (current) => ({ ...current, azimuth: current.azimuth - TURN_STEP }),\n      ArrowUp: (current) => ({ ...current, polar: current.polar + TILT_STEP }),\n      ArrowDown: (current) => ({ ...current, polar: current.polar - TILT_STEP }),\n      \"+\": (current) => ({ ...current, zoom: current.zoom * ZOOM_STEP }),\n      \"=\": (current) => ({ ...current, zoom: current.zoom * ZOOM_STEP }),\n      \"-\": (current) => ({ ...current, zoom: current.zoom / ZOOM_STEP }),\n      _: (current) => ({ ...current, zoom: current.zoom / ZOOM_STEP }),\n      Home: () => defaultView,\n    };\n    const change = changes[event.key];\n    if (!change) return;\n    event.preventDefault();\n    act(change);\n  };\n\n  const round = (value: number): string => String(Math.round(value * 100) / 100);\n\n  return (\n    <ModelViewerContext\n      value={{\n        status,\n        progress,\n        view,\n        labels,\n        act,\n        reset,\n        autoRotate: autoRotate && !reduced,\n        turning,\n        setTurning,\n        src,\n        kind,\n        ar,\n        // eslint-disable-next-line @next/next/no-img-element -- The library is not tied to one framework: a poster given as an address is a plain element, and `poster` also takes an element (the framework's image component).\n        poster: typeof poster === \"string\" ? <img src={poster} alt=\"\" draggable={false} className=\"size-full object-contain\" /> : poster,\n      }}\n    >\n      <div\n        ref={setRoot}\n        data-slot=\"model-viewer\"\n        data-state={status}\n        data-kind={kind}\n        data-azimuth={round(view.azimuth)}\n        data-polar={round(view.polar)}\n        data-zoom={round(view.zoom)}\n        data-turning={spinning ? \"\" : undefined}\n        className={cn(\"relative isolate w-full overflow-hidden rounded-surface border bg-muted\", aspect === \"auto\" && \"h-full\", className)}\n        style={aspect === \"auto\" ? style : { aspectRatio: String(aspect), ...style }}\n        {...props}\n      >\n        <div\n          ref={setHost}\n          data-slot=\"model-viewer-surface\"\n          // Ready, it is a widget with its own keys; before that (and where 3D cannot run) it is a picture with a name.\n          role={ready ? \"application\" : \"img\"}\n          aria-roledescription={ready ? labels.roledescription : undefined}\n          aria-label={alt}\n          aria-describedby={ready ? instructions : undefined}\n          tabIndex={ready ? 0 : undefined}\n          onKeyDown={handleKeyDown}\n          onPointerDown={handlePointerDown}\n          onPointerMove={handlePointerMove}\n          onPointerUp={handlePointerEnd}\n          onPointerCancel={handlePointerEnd}\n          className={cn(\n            \"absolute inset-0 touch-pan-y transition-opacity duration-slow ease-out select-none motion-reduce:transition-none\",\n            ready ? \"cursor-grab active:cursor-grabbing\" : \"opacity-0\",\n          )}\n        />\n        <p id={instructions} hidden>\n          {labels.instructions}\n        </p>\n        <ModelViewerPoster />\n        <ModelViewerStatusLine fallback={fallback} />\n        {children === undefined ? (\n          <>\n            <ModelViewerControls />\n            {ar ? <ModelViewerArButton /> : null}\n          </>\n        ) : (\n          children\n        )}\n      </div>\n    </ModelViewerContext>\n  );\n}\n\n/** The still: over the frame until the model has drawn, and for good when it cannot. It lets the pointer through. */\nfunction ModelViewerPoster() {\n  const { status, poster } = useModelViewer(\"ModelViewerPoster\");\n  if (!poster) return null;\n  return (\n    <div\n      data-slot=\"model-viewer-poster\"\n      aria-hidden=\"true\"\n      className={cn(\"pointer-events-none absolute inset-0 transition-opacity duration-slow ease-out motion-reduce:transition-none\", status === \"ready\" && \"opacity-0\")}\n    >\n      {poster}\n    </div>\n  );\n}\n\n/** Progress while the file loads; a sentence on a solid ground when it failed or 3D cannot run. */\nfunction ModelViewerStatusLine({ fallback }: { fallback: ReactNode }) {\n  const { status, progress, labels } = useModelViewer(\"ModelViewerStatusLine\");\n  if (status === \"loading\") {\n    return (\n      <div data-slot=\"model-viewer-progress\" className=\"pointer-events-none absolute inset-x-3 bottom-3\">\n        <Progress size=\"sm\" value={progress === null ? null : Math.round(progress * 100)} aria-label={labels.loading} className=\"border border-border-strong bg-background\" />\n      </div>\n    );\n  }\n  if (status !== \"error\" && status !== \"unsupported\") return null;\n  return (\n    <div data-slot=\"model-viewer-message\" className=\"absolute inset-x-3 bottom-3 rounded-control border border-border-strong bg-background px-3 py-2 text-sm text-foreground\">\n      {fallback ?? <p>{status === \"error\" ? labels.failed : labels.unsupported}</p>}\n    </div>\n  );\n}\n\nconst actionClass =\n  \"inline-flex size-(--control-h) shrink-0 items-center justify-center rounded-control border border-border-strong bg-background text-foreground transition-colors duration-instant ease-out hover:bg-accent disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none [&_svg]:size-4\";\n\nexport type ModelViewerControlsProps = ComponentProps<\"div\">;\n\n/**\n * The buttons, along the bottom of the frame: everything a drag or a pinch does, without one. Shown once\n * the model is ready. Default: turn left, turn right, zoom out, zoom in, reset, and stop or start when the\n * viewer turns by itself. Pass ModelViewerAction children to choose your own.\n */\nexport function ModelViewerControls({ className, children, ...props }: ModelViewerControlsProps) {\n  const { status, labels, autoRotate } = useModelViewer(\"ModelViewerControls\");\n  if (status !== \"ready\") return null;\n  return (\n    <div\n      data-slot=\"model-viewer-controls\"\n      role=\"group\"\n      aria-label={labels.controls}\n      // Buttons that turn left and right keep their sides in every language, as the model does.\n      dir=\"ltr\"\n      className={cn(\"absolute inset-x-2 bottom-2 flex flex-wrap items-center justify-center gap-1\", className)}\n      {...props}\n    >\n      {children ?? (\n        <>\n          <ModelViewerAction action=\"turn-left\" />\n          <ModelViewerAction action=\"turn-right\" />\n          <ModelViewerAction action=\"zoom-out\" />\n          <ModelViewerAction action=\"zoom-in\" />\n          <ModelViewerAction action=\"reset\" />\n          {autoRotate ? <ModelViewerAction action=\"turning\" /> : null}\n        </>\n      )}\n    </div>\n  );\n}\n\nexport type ModelViewerActionProps = Omit<ComponentProps<\"button\">, \"type\"> & {\n  action: \"turn-left\" | \"turn-right\" | \"zoom-in\" | \"zoom-out\" | \"reset\" | \"turning\";\n};\n\n/** One button of the viewer. Its name comes from the viewer's `labels`; children replace its icon. */\nexport function ModelViewerAction({ className, action, children, onClick, ...props }: ModelViewerActionProps) {\n  const { labels, act, reset, turning, setTurning, status } = useModelViewer(\"ModelViewerAction\");\n  const actions = {\n    \"turn-left\": { label: labels.turnLeft, icon: <ArrowLeft />, run: () => act((view) => ({ ...view, azimuth: view.azimuth - TURN_STEP })) },\n    \"turn-right\": { label: labels.turnRight, icon: <ArrowRight />, run: () => act((view) => ({ ...view, azimuth: view.azimuth + TURN_STEP })) },\n    \"zoom-in\": { label: labels.zoomIn, icon: <Plus />, run: () => act((view) => ({ ...view, zoom: view.zoom * ZOOM_STEP })) },\n    \"zoom-out\": { label: labels.zoomOut, icon: <Minus />, run: () => act((view) => ({ ...view, zoom: view.zoom / ZOOM_STEP })) },\n    reset: { label: labels.reset, icon: <RotateCcw />, run: reset },\n    turning: { label: turning ? labels.stopTurning : labels.startTurning, icon: turning ? <Pause /> : <Play />, run: () => setTurning(!turning) },\n  }[action];\n  return (\n    <button\n      type=\"button\"\n      data-slot=\"model-viewer-action\"\n      data-action={action}\n      aria-label={actions.label}\n      disabled={status !== \"ready\"}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) actions.run();\n      }}\n      className={cn(actionClass, className)}\n      {...props}\n    >\n      {children ?? <span aria-hidden=\"true\">{actions.icon}</span>}\n    </button>\n  );\n}\n\nconst noPlatform = (): ArPlatform => \"none\";\n\nexport type ModelViewerArButtonProps = Omit<ComponentProps<\"a\">, \"href\" | \"rel\">;\n\n/**\n * The hand-off to the phone's own AR viewer, at the top of the frame. It renders nothing where there is\n * none. On iPhone and iPad it opens the viewer's `ar.usdz` in AR Quick Look; on Android it opens `ar.glb`\n * (or the viewer's own glTF file) in Scene Viewer, which needs an absolute https address and falls back to\n * this page when the app is missing. Splats have no AR viewer to be handed to: give a mesh for it.\n */\nexport function ModelViewerArButton({ className, children, onClick, ...props }: ModelViewerArButtonProps) {\n  const { ar, labels, src, kind } = useModelViewer(\"ModelViewerArButton\");\n  const platform = useSyncExternalStore(never, readArPlatform, noPlatform);\n  const file = platform === \"quicklook\" ? ar?.usdz : platform === \"sceneviewer\" ? (ar?.glb ?? (kind === \"gltf\" ? src : undefined)) : undefined;\n  if (!file) return null;\n\n  let href = file;\n  if (platform === \"sceneviewer\") {\n    const absolute = new URL(file, window.location.href).toString();\n    const query = new URLSearchParams({ file: absolute, mode: \"ar_preferred\" });\n    if (ar?.title) query.set(\"title\", ar.title);\n    href = `intent://arvr.google.com/scene-viewer/1.0?${query.toString()}#Intent;scheme=https;package=com.google.android.googlequicksearchbox;action=android.intent.action.VIEW;S.browser_fallback_url=${encodeURIComponent(window.location.href)};end;`;\n  }\n  return (\n    <a\n      data-slot=\"model-viewer-ar\"\n      data-platform={platform}\n      href={href}\n      rel={platform === \"quicklook\" ? \"ar\" : undefined}\n      onClick={(event) => {\n        onClick?.(event);\n        if (platform !== \"quicklook\" || event.defaultPrevented) return;\n        // Quick Look opens in place only from a link whose one child is a picture, so that link is made for the press.\n        event.preventDefault();\n        const link = document.createElement(\"a\");\n        link.rel = \"ar\";\n        link.href = file;\n        link.append(document.createElement(\"img\"));\n        link.click();\n      }}\n      className={cn(\n        \"absolute end-2 top-2 inline-flex h-control items-center gap-2 rounded-control border border-border-strong bg-background px-3 text-sm font-medium text-foreground transition-colors duration-instant ease-out hover:bg-accent motion-reduce:transition-none [&_svg]:size-4\",\n        className,\n      )}\n      {...props}\n    >\n      {children ?? (\n        <>\n          <Box aria-hidden=\"true\" />\n          {labels.ar}\n        </>\n      )}\n    </a>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "three",
    "when": "A file to look at from every side: an object, a product, a scanned place. It is a whole viewer, not a part of scene: for your own meshes inside a react-three-fiber canvas use scene with model-stage. Nothing heavy is in this file: three.js is fetched when the viewer comes near the screen, its glTF loader only for glTF, and Spark (`@sparkjsdev/spark`, installed with this item) only when the file is splats. glTF that carries splats in an extension is not read (Spark has no glTF loader); Draco, Meshopt and KTX2 compression need their decoders set in `configureLoader`. Plain wheel and vertical swipes scroll the page: zoom is pinch, Ctrl with the wheel, the keys or the buttons. To compare two models, give two viewers the same `view` and `bounds` inside compare-slider, with `children={null}` and buttons of your own that change the shared view.",
    "example": "<ModelViewer src=\"/models/vase.glb\" alt=\"A clay vase with a painted belt\" poster=\"/models/vase.jpg\" />\n\n// Splats, turning by itself (never under reduced motion), with a hand-off to AR on phones\n<ModelViewer\n  src=\"/models/courtyard.spz\"\n  alt=\"The courtyard, scanned in 2026\"\n  autoRotate\n  rotation={[180, 0, 0]}\n  ar={{ usdz: \"/models/courtyard.usdz\", glb: \"https://example.com/models/courtyard.glb\" }}\n/>\n\n// Two viewers, one camera\nconst [view, setView] = useState<ModelView>({ azimuth: 0, polar: 15, zoom: 1 });\nconst frame = { center: [0, 4, 0], radius: 9 } as const; // one sphere for both, so they keep their sizes and line up\n<ModelViewer src=\"/models/then.glb\" alt=\"As built\" view={view} onViewChange={setView} bounds={frame} />\n<ModelViewer src=\"/models/now.glb\" alt=\"Today\" view={view} onViewChange={setView} bounds={frame} />",
    "client": true
  }
}
