@webspatial/react-sdk 1.7.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +265 -4
- package/dist/Model-DO5ps8NA.d.ts +35 -0
- package/dist/Reality-BDyKL6th.d.ts +256 -0
- package/dist/Reality-DO-itiWW.d.ts +33 -0
- package/dist/SceneGraph-DxH74y6-.d.ts +214 -0
- package/dist/chunk-6JSRUX7P.js +2 -0
- package/dist/chunk-6JSRUX7P.js.map +1 -0
- package/dist/chunk-BTLTBCA7.js +2 -0
- package/dist/chunk-BTLTBCA7.js.map +1 -0
- package/dist/chunk-GG2QK5MA.js +2 -0
- package/dist/chunk-GG2QK5MA.js.map +1 -0
- package/dist/chunk-IOLNY4GP.js +2 -0
- package/dist/chunk-IOLNY4GP.js.map +1 -0
- package/dist/chunk-NWVQY6CN.js +2 -0
- package/dist/chunk-NWVQY6CN.js.map +1 -0
- package/dist/chunk-NXEOIP4Z.js +2 -0
- package/dist/chunk-NXEOIP4Z.js.map +1 -0
- package/dist/chunk-PDUEHFTO.js +2 -0
- package/dist/chunk-PDUEHFTO.js.map +1 -0
- package/dist/chunk-QHUROD77.js +2 -0
- package/dist/chunk-QHUROD77.js.map +1 -0
- package/dist/chunk-UHEO47WY.js +2 -0
- package/dist/chunk-UHEO47WY.js.map +1 -0
- package/dist/chunk-WDOPCAA3.js +19 -0
- package/dist/chunk-WDOPCAA3.js.map +1 -0
- package/dist/eager.d.ts +46 -0
- package/dist/eager.js +8 -0
- package/dist/eager.js.map +1 -0
- package/dist/experimental.d.ts +24 -0
- package/dist/experimental.js +8 -0
- package/dist/experimental.js.map +1 -0
- package/dist/index.d.ts +70 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/facades-client.d.ts +50 -0
- package/dist/internal/facades-client.js +3 -0
- package/dist/internal/facades-client.js.map +1 -0
- package/dist/jsx/jsx-dev-runtime.d.ts +7 -83
- package/dist/jsx/jsx-dev-runtime.js +1 -67
- package/dist/jsx/jsx-dev-runtime.js.map +1 -1
- package/dist/jsx/jsx-runtime.d.ts +81 -2
- package/dist/jsx/jsx-runtime.js +1 -67
- package/dist/jsx/jsx-runtime.js.map +1 -1
- package/dist/jsx-shared-CFDVUVpc.d.ts +16 -0
- package/dist/motionBindingTypes-CjxIC5bP.d.ts +25 -0
- package/dist/runtime/registerEagerEntry.d.ts +8 -0
- package/dist/runtime/registerEagerEntry.js +2 -0
- package/dist/runtime/registerEagerEntry.js.map +1 -0
- package/dist/spatial.d.ts +25 -0
- package/dist/spatial.js +7 -0
- package/dist/spatial.js.map +1 -0
- package/dist/useAnimation-C1LXt-xO.d.ts +28 -0
- package/dist/useMetrics-Bm_Urbtp.d.ts +96 -0
- package/package.json +51 -31
- package/dist/default/index.d.ts +0 -475
- package/dist/default/index.js +0 -4269
- package/dist/default/index.js.map +0 -1
- package/dist/jsx/jsx-dev-runtime.web.d.ts +0 -2
- package/dist/jsx/jsx-dev-runtime.web.js +0 -18
- package/dist/jsx/jsx-dev-runtime.web.js.map +0 -1
- package/dist/jsx/jsx-runtime.web.d.ts +0 -1
- package/dist/jsx/jsx-runtime.web.js +0 -18
- package/dist/jsx/jsx-runtime.web.js.map +0 -1
- package/dist/web/index.d.ts +0 -475
- package/dist/web/index.js +0 -4333
- package/dist/web/index.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/spatial/index.ts","../src/spatialized-container/hooks/use2DFrameDetector.ts","../src/spatialized-container/context/SpatializedContainerContext.ts","../src/spatialized-container/SpatialID.ts","../src/spatialized-container/StandardSpatializedContainer.tsx","../src/spatialized-container/TransformVisibilityTaskContainer.tsx","../src/spatialized-container/hooks/useSpatialTransformVisibility.ts","../src/notifyUpdateStandInstanceLayout.ts","../src/spatialized-container/SpatializedContainer.tsx","../src/utils/getSession.ts","../src/spatialized-container/context/SpatialLayerContext.ts","../src/spatialized-container/PortalSpatializedContainer.tsx","../src/spatialized-container/context/PortalInstanceContext.ts","../src/spatialized-container/utils.ts","../src/spatialized-container/types.ts","../src/spatialized-container/hooks/useSync2DFrame.ts","../src/utils/windowStyleSync.ts","../src/spatialized-container/hooks/useSpatializedElement.ts","../src/spatialized-container/motion/useBindSpatializedMotion.ts","../src/spatialized-container/hooks/useDomProxy.ts","../src/reality/context/InsideAttachmentContext.tsx","../src/spatialized-container/hooks/useSpatialEvents.ts","../src/spatialized-container/Spatialized2DElementContainer.tsx","../src/utils/useSyncHeadStyles.ts","../src/spatialized-container/hooks/useSpatialContentReady.ts","../src/spatialized-container/SpatializedStatic3DElementContainer.tsx","../src/spatialized-container/Spatialized2DElementContainerFactory.tsx","../src/spatialized-container/motion/useAnimation.ts","../src/spatialized-container/motion/motionConfigSignature.ts","../src/spatialized-container/motion/AnimationBinding.ts","../src/spatialized-container/motion/style.ts","../src/spatialized-container/index.ts","../src/Model.tsx","../src/reality/components/Entity.tsx","../src/reality/components/BaseEntity.tsx","../src/reality/context/RealityContext.tsx","../src/reality/context/ParentContext.tsx","../src/reality/context/AttachmentContext.tsx","../src/reality/hooks/useEntityTransform.tsx","../src/reality/utils/ResourceRegistry.ts","../src/reality/utils/equal.ts","../src/reality/utils/AbortResourceManager.ts","../src/reality/hooks/useEntityEvent.tsx","../src/reality/type.ts","../src/reality/hooks/useEntityRef.tsx","../src/reality/hooks/useRealityEvents.tsx","../src/reality/hooks/useEntityId.tsx","../src/reality/hooks/useEntity.tsx","../src/reality/hooks/useForceUpdate.tsx","../src/reality/hooks/useAnimation.ts","../src/reality/hooks/animationValidator.ts","../src/reality/components/BoxEntity.tsx","../src/reality/components/GeometryEntity.tsx","../src/reality/components/UnlitMaterial.tsx","../src/reality/components/Texture.tsx","../src/internal/urlUtils.ts","../src/reality/components/SphereEntity.tsx","../src/reality/components/ConeEntity.tsx","../src/reality/components/CylinderEntity.tsx","../src/reality/components/PlaneEntity.tsx","../src/reality/components/SceneGraph.tsx","../src/reality/components/ModelAsset.tsx","../src/reality/components/ModelEntity.tsx","../src/reality/components/Reality.tsx","../src/reality/components/AttachmentAsset.tsx","../src/reality/components/AttachmentEntity.tsx","../src/reality/components/Material.tsx","../src/useMetrics.tsx","../src/spatialized-container-monitor/withSpatialMonitor.tsx","../src/spatialized-container-monitor/useMonitorDomChange.tsx","../src/spatialized-container-monitor/useMonitorDocumentHeaderChange.tsx","../src/spatialized-container-monitor/SpatialMonitor.tsx"],"sourcesContent":["// =============================================================================\n// `@webspatial/react-sdk/spatial` — bridge-facing spatial namespace.\n//\n// This module is the dynamic-import target invoked by\n// `runtime/bridge.ts#loadSpatialImpl()`. It exposes ONLY the real\n// implementations that default-entry facades need to resolve by name:\n// real `Model`, `Reality`, `Entity`, all `*Entity` components,\n// materials / assets, `SceneGraph` / `World`, the real\n// `withSpatialized2DElementContainer` / `withSpatialMonitor` HOCs, and the\n// real `useMetrics`. Per spec tasks.md §3.2, internal containers / monitors\n// (`SpatializedContainer`, `Spatialized2DElementContainer`,\n// `SpatializedStatic3DElementContainer`, `SpatialMonitor`) and internal\n// reality hooks (`useEntity`, `useEntityRef`, `useEntityTransform`,\n// `useEntityEvent`, `useEntityId`, `useRealityEvents`, `useForceUpdate`)\n// are NOT exposed here even though they are reachable from the spatial\n// chunk's static module graph — they are facade-HOC implementation details.\n//\n// Phasing note (spec tasks.md §3.2): until §3.1's physical file relocation\n// lands, the re-export targets remain pointed at the existing source paths\n// (`../Model`, `../reality`, etc.); the runtime module-graph contract is\n// nevertheless satisfied because `src/index.ts` (the default entry) no\n// longer statically imports any of these paths — they are reachable ONLY\n// through this module, which the bridge dynamic-imports.\n// =============================================================================\n\n// Spatial chunk bootstrap: install the `@webspatial/core-sdk` scene hook +\n// `window.spatial` polyfill. Per the lazy-load proposal `tasks.md §12.9`\n// (\"Pre-v1 budget calibration\") this opt-in subpath replaces what used\n// to be `core-sdk/index.ts`'s top-level side effect — the spatial chunk\n// is the right place to install those polyfills because they are only\n// observable in WebSpatial-capable browsers, AND because dynamic-loading\n// them here means the SDK's lean default-entry bundle never has to pull\n// `scene-polyfill.ts` (~636 LoC) into its static module graph.\nimport '@webspatial/core-sdk/install-polyfills'\n\nimport { initPolyfill } from '../spatialized-container'\n\nexport * from '../Model'\nexport * from '../reality'\nexport { useMetrics } from '../useMetrics'\nexport { useAnimation } from '../spatialized-container/motion'\nexport { useEntityAnimation } from '../reality/hooks/useAnimation'\nexport { withSpatialized2DElementContainer } from '../spatialized-container'\nexport { withSpatialMonitor } from '../spatialized-container-monitor'\n\n// Re-export `getSession` so the default-entry utilities (`enableDebugTool`,\n// `convertCoordinate`, `initScene`) can route their `getSession()` calls\n// through the bridge instead of statically importing the real\n// implementation. The static import would pull `Spatial` + `SpatialSession`\n// — and through `SpatialSession`'s class body, every geometry creator,\n// `SpatialEntity`, `realityCreator`, `Attachment`, etc. — into the\n// default-entry bundle, blowing the marginal-delta budget. Routing\n// through `getSpatialImpl()?.getSession?.()` keeps the chain reachable\n// only via the dynamic `import('./spatial')` from the bridge.\n//\n// Per `tasks.md §12.9` calibration follow-up.\nexport { getSession } from '../utils/getSession'\n\n// Spatial chunk bootstrap: install the CSS parser + default-style polyfill\n// when the spatial chunk loads. Per spec tasks.md §7.2 this side effect\n// MUST live inside the spatial chunk, NOT in the default entry — the\n// default entry's previous top-level `if (typeof window !== 'undefined')\n// initPolyfill()` was removed in PR 4 (per \"No observable top-level\n// side effects in default-entry modules\" Scenario of the Tree-shake\n// friendliness Requirement).\nif (typeof window !== 'undefined') {\n initPolyfill()\n}\n","import {\n useContext,\n useLayoutEffect,\n useEffect,\n useCallback,\n MutableRefObject,\n} from 'react'\n\nimport {\n SpatializedContainerContext,\n SpatializedContainerObject,\n} from '../context/SpatializedContainerContext'\n\nexport function use2DFrameDetector(ref: MutableRefObject<HTMLElement | null>) {\n const spatializedContainerObject: SpatializedContainerObject = useContext(\n SpatializedContainerContext,\n )!\n\n const notify2DFrameChange = useCallback(() => {\n ref.current &&\n spatializedContainerObject.notify2DFramePlaceHolderChange(ref.current)\n }, [ref.current, spatializedContainerObject])\n\n useLayoutEffect(notify2DFrameChange, [notify2DFrameChange])\n\n // listen to webview container size change and notifyDomChange\n // document.body.clientWidth may change as page loads.\n // when creating a new scene, clientWidth changes from 0 to some positive value.\n // this cannot be detected by ResizeObserver which only observe the dom element itself\n useEffect(() => {\n if (!ref.current || !spatializedContainerObject) {\n console.warn(\n 'Ref is not attached to the DOM or spatializedContainerObject is not available',\n )\n return\n }\n\n window.addEventListener('resize', notify2DFrameChange)\n\n return () => {\n window.removeEventListener('resize', notify2DFrameChange)\n }\n }, [])\n\n // detect dom resize\n // Trigger native resize on web resize events\n useEffect(() => {\n if (!ref.current) {\n console.warn('Ref is not attached to the DOM')\n return\n }\n\n const ro = new ResizeObserver(notify2DFrameChange)\n ro.observe(ref.current!)\n return () => {\n ro.disconnect()\n }\n }, [])\n\n // detect dom style and class change\n useEffect(() => {\n if (!ref.current) {\n console.warn('Ref is not attached to the DOM')\n return\n }\n const ro = new MutationObserver(notify2DFrameChange)\n ro.observe(ref.current!, {\n attributeFilter: ['class', 'style'],\n subtree: true,\n })\n return () => {\n ro.disconnect()\n }\n }, [])\n}\n","import { createContext } from 'react'\nimport { SpatialID } from '../SpatialID'\nimport { SpatializedElementRef, SpatialTransformVisibility } from '../types'\nimport { SpatialContainerRefProxy } from '../hooks/useDomProxy'\n\nexport class SpatializedContainerObject<\n T extends SpatializedElementRef = SpatializedElementRef,\n> {\n dom: HTMLElement | null = null\n domSpatialId: string | null = null\n\n private fns: Record<string, () => void> = {}\n // cache dom for each spatialId\n private spatialId2dom: Record<string, HTMLElement> = {}\n private spatialId2parentSpatialDom: Record<string, HTMLElement> = {}\n\n // layer : [standardInstance sequence, portalInstance sequence]\n private layerSequences: Record<number, [number, number]> = {}\n\n public notify2DFramePlaceHolderChange(dom: HTMLElement) {\n this.dom = dom\n this.domSpatialId = dom.getAttribute(SpatialID)\n Object.values(this.fns).forEach(fn => fn())\n }\n\n private spatialId2transformVisibility: Record<\n string,\n SpatialTransformVisibility\n > = {}\n public updateSpatialTransformVisibility(\n spatialId: string,\n spatialTransformVisibility: SpatialTransformVisibility,\n ) {\n this.spatialId2transformVisibility[spatialId] = spatialTransformVisibility\n // notify\n this.fnsForSpatialTransformVisibility[spatialId]?.forEach(fn =>\n fn(spatialTransformVisibility),\n )\n }\n\n // this is used by onSpatialEvent.currentTarget property\n private spatialId2ContainerRefProxy: Record<\n string,\n SpatialContainerRefProxy<T>\n > = {}\n\n // this is called in sub standardInstance env\n public updateSpatialContainerRefProxyInfo(\n spatialId: string,\n spatialContainerRefProxy: SpatialContainerRefProxy<T>,\n ) {\n this.spatialId2ContainerRefProxy[spatialId] =\n spatialContainerRefProxy as unknown as SpatialContainerRefProxy<T>\n }\n\n public getSpatialContainerRefProxyBySpatialId<\n T extends SpatializedElementRef,\n >(spatialId: string) {\n return this.spatialId2ContainerRefProxy[\n spatialId\n ] as unknown as SpatialContainerRefProxy<T>\n }\n\n // notify when TransformVisibilityTaskContainer data change\n private fnsForSpatialTransformVisibility: Record<\n string,\n Array<(spatialTransformVisibility: SpatialTransformVisibility) => void>\n > = {}\n\n // used by StandardSpatializedContainer and PortalSpatializedContainer\n public onSpatialTransformVisibilityChange(\n spatialId: string,\n fn: (spatialTransformVisibility: SpatialTransformVisibility) => void,\n ) {\n if (!this.fnsForSpatialTransformVisibility[spatialId]) {\n this.fnsForSpatialTransformVisibility[spatialId] = []\n }\n this.fnsForSpatialTransformVisibility[spatialId].push(fn)\n if (this.spatialId2transformVisibility[spatialId]) {\n fn(this.spatialId2transformVisibility[spatialId])\n }\n }\n\n public offSpatialTransformVisibilityChange(\n spatialId: string,\n fn: (spatialTransformVisibility: SpatialTransformVisibility) => void,\n ) {\n const fns = this.fnsForSpatialTransformVisibility[spatialId]\n if (fns) {\n this.fnsForSpatialTransformVisibility[spatialId] = fns.filter(\n f => f !== fn,\n )\n }\n }\n\n public on2DFrameChange(spatialId: string, fn: () => void) {\n this.fns[spatialId] = fn\n if (this.dom) {\n fn()\n }\n }\n\n public off2DFrameChange(spatialId: string) {\n delete this.fns[spatialId]\n delete this.spatialId2dom[spatialId]\n delete this.spatialId2parentSpatialDom[spatialId]\n }\n\n public querySpatialDomBySpatialId(spatialId: string) {\n if (this.domSpatialId === spatialId) {\n return this.dom\n }\n if (!this.dom) {\n return null\n }\n if (!this.spatialId2dom[spatialId]) {\n const spatialDom = this.dom.querySelector(`[${SpatialID}=\"${spatialId}\"]`)\n\n if (spatialDom) {\n this.spatialId2dom[spatialId] = spatialDom as HTMLElement\n }\n }\n return this.spatialId2dom[spatialId]\n }\n\n public queryParentSpatialDomBySpatialId(spatialId: string) {\n if (this.domSpatialId === spatialId) {\n return null\n }\n\n if (this.spatialId2parentSpatialDom[spatialId]) {\n // early return if already found\n return this.spatialId2parentSpatialDom[spatialId]\n }\n\n let spatialDom = this.querySpatialDomBySpatialId(spatialId)\n if (spatialDom) {\n if (spatialDom === this.dom) return null\n let parentSpatialDom = spatialDom.parentElement as HTMLElement\n while (parentSpatialDom && spatialDom !== this.dom) {\n if (parentSpatialDom.hasAttribute(SpatialID)) {\n break\n } else {\n parentSpatialDom = parentSpatialDom.parentElement as HTMLElement\n }\n }\n\n this.spatialId2parentSpatialDom[spatialId] = parentSpatialDom\n return parentSpatialDom\n }\n return null\n }\n\n public getSpatialId(\n layer: number,\n isInStandardInstance: boolean,\n name: string = '',\n ): string {\n if (this.layerSequences[layer] === undefined) {\n this.layerSequences[layer] = [0, 0]\n }\n const idx = isInStandardInstance ? 0 : 1\n const sequenceId = this.layerSequences[layer][idx]\n this.layerSequences[layer][idx] = sequenceId + 1\n const spatialId = `${name}_${layer}_${sequenceId}`\n return spatialId\n }\n}\n\nexport const SpatializedContainerContext =\n createContext<SpatializedContainerObject | null>(null)\n","export const SpatialID = 'data-spatial-id'\n","// Renders the standard host: the visible 2D placeholder of a spatial\n// container. The host is permanently hidden via class-scoped CSS rules\n// (`.xr-spatial-default[data-xr-host]`) and exposed to consumers as\n// `ref.current`. See `./ARCHITECTURE.md` for the invariants this component\n// must preserve and the reasoning behind the data-attribute / CSS approach.\nimport {\n SpatializedElementRef,\n SpatialTransformVisibility,\n StandardSpatializedContainerProps,\n} from './types'\nimport { use2DFrameDetector } from './hooks/use2DFrameDetector'\nimport {\n ForwardedRef,\n forwardRef,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n} from 'react'\nimport { SpatializedContainerContext } from './context/SpatializedContainerContext'\nimport { SpatialID } from './SpatialID'\n\nfunction useSpatialTransformVisibilityWatcher(spatialId: string) {\n const [transformExist, setTransformExist] = useState(false)\n\n const spatializedContainerObject = useContext(SpatializedContainerContext)!\n useEffect(() => {\n const fn = (spatialTransform: SpatialTransformVisibility) => {\n setTransformExist(spatialTransform.transform !== 'none')\n }\n spatializedContainerObject.onSpatialTransformVisibilityChange(spatialId, fn)\n return () => {\n spatializedContainerObject.offSpatialTransformVisibilityChange(\n spatialId,\n fn,\n )\n }\n }, [spatialId, spatializedContainerObject])\n\n return transformExist\n}\n\nfunction useInternalRef(ref: ForwardedRef<HTMLElement | null>) {\n const refInternal = useRef<HTMLElement | null>(null)\n const refInternalCallback = useCallback(\n (node: HTMLElement | null) => {\n refInternal.current = node\n\n if (typeof ref === 'function') {\n ref(node)\n } else if (ref) {\n ref.current = node\n }\n },\n [ref],\n )\n\n return { refInternal, refInternalCallback }\n}\n\nexport function StandardSpatializedContainerBase(\n props: StandardSpatializedContainerProps,\n ref: ForwardedRef<HTMLElement | null>,\n) {\n const {\n component: Component,\n style: inStyle = {},\n className,\n inStandardSpatializedContainer = false,\n ...restProps\n } = props\n\n const { refInternal, refInternalCallback } = useInternalRef(ref)\n if (!inStandardSpatializedContainer) {\n use2DFrameDetector(refInternal)\n }\n const transformExist = useSpatialTransformVisibilityWatcher(props[SpatialID])\n\n const classNames = className\n ? `${className} xr-spatial-default`\n : 'xr-spatial-default'\n\n // Apply spatial host appearance (visibility / transition / transform) via a\n // CSS rule scoped to `.xr-spatial-default[data-xr-host]`, NOT via inline\n // style. The standard host has a styleProxy installed on it (see\n // SpatialContainerRefProxy) that forwards `style.transform` /\n // `style.visibility` writes to the probe so user code like\n // `ref.current.style.transform = 'rotate(45deg)'` reaches the platform\n // layer. If we wrote `transform: translateZ(0)` inline here, React's commit\n // would hit that proxy and clobber the user's value on the probe\n // (https://github.com/webspatial/webspatial-sdk/pull/1194).\n //\n // The SDK-controlled `data-xr-host` / `data-xr-transform-active` attributes\n // are placed AFTER `restProps` so user-supplied values cannot override\n // them — losing `data-xr-host` would un-hide the 2D placeholder, and\n // forcing `data-xr-transform-active` would diverge the host's stacking\n // state from the spatial transform watcher.\n return (\n <Component\n ref={refInternalCallback}\n style={inStyle}\n className={classNames}\n {...restProps}\n data-xr-host=\"\"\n data-xr-transform-active={transformExist ? '' : undefined}\n />\n )\n}\n\nexport const StandardSpatializedContainer = forwardRef(\n StandardSpatializedContainerBase,\n) as <T extends SpatializedElementRef>(\n props: StandardSpatializedContainerProps & {\n ref?: ForwardedRef<SpatializedElementRef<T>>\n },\n) => React.ReactElement | null\n\n/**\n * The hidden-host rules apply only to the visible 2D placeholder\n * (StandardSpatializedContainer's host element). They are intentionally\n * NOT written as inline style on that element — see the comment in\n * StandardSpatializedContainerBase. The selector is scoped via\n * `.xr-spatial-default` (always present on a spatial host) so that\n * unrelated DOM that happens to carry a `data-xr-host` attribute is not\n * affected. `!important` matches the previous inline-style behavior\n * where user-supplied inline visibility/transform could not override the\n * host's hidden / stacking-context state. The class observer mirrors\n * `class` (not `data-*`) onto the probe, so the probe never matches\n * because it lacks `data-xr-host`.\n */\nconst SPATIAL_DEFAULT_STYLE_CSS = `\n :where(.xr-spatial-default) {\n --xr-back: 0;\n --xr-depth: 0;\n --xr-z-index: 0;\n --xr-background-material: none;\n }\n .xr-spatial-default[data-xr-host] {\n visibility: hidden !important;\n transition: none !important;\n transform: none !important;\n }\n .xr-spatial-default[data-xr-host][data-xr-transform-active] {\n transform: translateZ(0) !important;\n }\n`\n\n/**\n * Marker attribute used to dedupe injected stylesheets per root.\n * Anyone querying for `style[data-xr-spatial-default-style]` should be able\n * to find the SDK's stylesheet and skip re-injecting.\n */\nconst SPATIAL_DEFAULT_STYLE_MARKER = 'data-xr-spatial-default-style'\n\n/**\n * Idempotently install the spatial default stylesheet into a tree root.\n *\n * Document-level stylesheets do not cross shadow boundaries, so a spatial\n * container rendered inside a `ShadowRoot` would miss the\n * `.xr-spatial-default[data-xr-host]` hiding rule and show the bare 2D\n * placeholder. Calling this for each host's root (Document or ShadowRoot)\n * keeps the rules reachable wherever the host actually lives.\n *\n * Safe to call repeatedly for the same root — uses an attribute marker on\n * the inserted `<style>` element to short-circuit duplicates.\n */\nexport function ensureSpatialDefaultStyleInRoot(root: Document | ShadowRoot) {\n const queryRoot = root === document ? document.head : root\n if (queryRoot.querySelector(`style[${SPATIAL_DEFAULT_STYLE_MARKER}]`)) {\n return\n }\n const ownerDoc =\n root === document\n ? document\n : (root as ShadowRoot).ownerDocument || document\n const styleElement = ownerDoc.createElement('style')\n styleElement.type = 'text/css'\n styleElement.setAttribute(SPATIAL_DEFAULT_STYLE_MARKER, '')\n styleElement.innerHTML = SPATIAL_DEFAULT_STYLE_CSS\n if (root === document) {\n document.head.appendChild(styleElement)\n } else {\n ;(root as ShadowRoot).appendChild(styleElement)\n }\n}\n\n/**\n * Polyfill entry point: ensure the document carries the spatial default\n * stylesheet. Hosts mounted inside shadow roots are covered by a separate\n * per-mount call from `SpatialContainerRefProxy`. Kept as a stable export\n * because it is referenced by `initPolyfill`.\n */\nexport function injectSpatialDefaultStyle() {\n ensureSpatialDefaultStyleInRoot(document)\n}\n","import {\n createElement,\n forwardRef,\n type CSSProperties,\n type ElementType,\n type ForwardedRef,\n useCallback,\n useRef,\n} from 'react'\nimport { SpatialID } from './SpatialID'\nimport { createPortal } from 'react-dom'\nimport { useSpatialTransformVisibility } from './hooks/useSpatialTransformVisibility'\n\n// used as root container for all TransformVisibilityTaskContainer\nlet cssParserDivContainer: HTMLDivElement | null = null\n\nexport function initCSSParserDivContainer() {\n cssParserDivContainer = document?.createElement('div')\n if (cssParserDivContainer) {\n cssParserDivContainer.style.position = 'absolute'\n cssParserDivContainer.setAttribute('data-id', 'css-parser-div-container')\n }\n}\n\nfunction createOrGetCSSParserDivContainer() {\n if (cssParserDivContainer && !cssParserDivContainer.parentElement) {\n document?.body.appendChild(cssParserDivContainer)\n }\n return cssParserDivContainer\n}\n\nfunction useInternalRef(ref: ForwardedRef<HTMLElement | null>) {\n const refInternal = useRef<HTMLElement | null>(null)\n const refInternalCallback = useCallback(\n (node: HTMLElement | null) => {\n refInternal.current = node\n\n if (typeof ref === 'function') {\n ref(node)\n } else if (ref) {\n ref.current = node\n }\n },\n [ref],\n )\n\n return { refInternal, refInternalCallback }\n}\n\ninterface TransformVisibilityTaskContainerProps {\n className?: string\n style?: CSSProperties\n /** Mirrors the spatial host intrinsic tag so tag selectors (e.g. `h1 {}`) apply to the probe. Non-string types fall back to `div`. */\n component?: ElementType\n [SpatialID]: string\n}\n\n/** Probe must be a real HTMLElement for getComputedStyle; custom components use `div`. */\nexport function resolveProbeIntrinsicTag(component?: ElementType): string {\n return typeof component === 'string' ? component : 'div'\n}\n\n// using css layout engine to calculate SpatializedContainer transform and visibility\nexport function TransformVisibilityTaskContainerBase(\n props: TransformVisibilityTaskContainerProps,\n ref: ForwardedRef<HTMLElement | null>,\n) {\n const { style: inStyle, component, ...restProps } = props\n const ProbeTag = resolveProbeIntrinsicTag(component)\n const extraStyle: CSSProperties = {\n // when width/height equal to zero, transform: translateX(-50%) won't work\n // to make sure the element is not visible, we set left/top to a very large negative value\n left: -10000,\n top: -10000,\n pointerEvents: 'none',\n opacity: 0,\n // width: 0,\n // height: 0,\n padding: 0,\n transition: 'none',\n position: 'absolute',\n }\n\n const { refInternal, refInternalCallback } = useInternalRef(ref)\n\n const style: CSSProperties = { ...inStyle, ...extraStyle }\n useSpatialTransformVisibility(props[SpatialID], refInternal)\n\n const cssParserDivContainer = createOrGetCSSParserDivContainer()\n\n if (!cssParserDivContainer) {\n return null\n }\n\n return createPortal(\n createElement(ProbeTag, {\n ref: refInternalCallback,\n style,\n ...restProps,\n }),\n cssParserDivContainer,\n )\n}\n\nexport const TransformVisibilityTaskContainer = forwardRef(\n TransformVisibilityTaskContainerBase,\n)\n","import { RefObject, useCallback, useContext, useEffect } from 'react'\nimport { SpatialStyleInfoUpdateEvent } from '../../notifyUpdateStandInstanceLayout'\nimport { SpatialTransformVisibility } from '../types'\nimport { SpatializedContainerContext } from '../context/SpatializedContainerContext'\n\nfunction parseTransformAndVisibilityProperties(\n node: HTMLElement,\n): SpatialTransformVisibility {\n const computedStyle = getComputedStyle(node)\n\n // handle transform properties\n const transform = computedStyle.getPropertyValue('transform')\n\n // parse visibility\n const visibility = computedStyle.getPropertyValue('visibility')\n\n return {\n visibility,\n transform,\n }\n}\n\nexport function useSpatialTransformVisibility(\n spatialId: string,\n ref: RefObject<HTMLElement | null>,\n) {\n const spatializedContainerObject = useContext(SpatializedContainerContext)!\n\n const checkSpatialStyleUpdate = useCallback(() => {\n if (!ref.current) {\n return\n }\n const spatialTransformVisibility = parseTransformAndVisibilityProperties(\n ref.current!,\n )\n\n // notify SpatializedContainerContext\n spatializedContainerObject.updateSpatialTransformVisibility(\n spatialId,\n spatialTransformVisibility,\n )\n }, [])\n\n useEffect(() => {\n checkSpatialStyleUpdate()\n }, [checkSpatialStyleUpdate])\n\n useEffect(() => {\n // sync spatial style when this dom or sub dom change\n const observer = new MutationObserver(mutationsList => {\n checkSpatialStyleUpdate()\n })\n const config = {\n childList: false,\n subtree: false,\n attributes: true,\n // attributeOldValue: true,\n attributeFilter: ['style', 'class'],\n }\n observer.observe(ref.current!, config)\n\n return () => {\n observer.disconnect()\n }\n }, [])\n\n useEffect(() => {\n const headObserver = new MutationObserver(mutations => {\n checkSpatialStyleUpdate()\n })\n headObserver.observe(document.head, { childList: true, subtree: true })\n return () => {\n headObserver.disconnect()\n }\n }, [])\n\n useEffect(() => {\n const onDomUpdated = (event: Event) => {\n checkSpatialStyleUpdate()\n }\n\n // check style property change when some external style change\n document.addEventListener(\n SpatialStyleInfoUpdateEvent.domUpdated,\n onDomUpdated,\n )\n\n return () => {\n document.removeEventListener(\n SpatialStyleInfoUpdateEvent.domUpdated,\n onDomUpdated,\n )\n }\n }, [])\n}\n","export enum SpatialStyleInfoUpdateEvent {\n standInstanceLayout = 'standInstanceLayout',\n domUpdated = 'domUpdated',\n}\n\n/**\n * External-developers can call this function to sync the standardInstance layout to PortalInstance.\n *\n * Currently: notifyUpdateStandInstanceLayout is called when the document head changed\n * or when the monitored div changed (in both cases spatialDiv's layout may be changed, so we need to update the layout)\n */\nexport function notifyUpdateStandInstanceLayout() {\n document.dispatchEvent(\n new CustomEvent(SpatialStyleInfoUpdateEvent.standInstanceLayout, {\n detail: {},\n }),\n )\n}\n\nexport function notifyDOMUpdate(mutationsList: MutationRecord[]) {\n document.dispatchEvent(\n new CustomEvent(SpatialStyleInfoUpdateEvent.domUpdated, {\n detail: mutationsList,\n }),\n )\n}\n","import {\n ForwardedRef,\n forwardRef,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from 'react'\nimport {\n SpatializedContainerContext,\n SpatializedContainerObject,\n} from './context/SpatializedContainerContext'\nimport { getSession } from '../utils/getSession'\nimport { SpatialLayerContext } from './context/SpatialLayerContext'\nimport { SpatializedElementRef, SpatializedContainerProps } from './types'\nimport { StandardSpatializedContainer } from './StandardSpatializedContainer'\nimport { PortalSpatializedContainer } from './PortalSpatializedContainer'\nimport { PortalInstanceContext } from './context/PortalInstanceContext'\nimport { SpatialID } from './SpatialID'\nimport { TransformVisibilityTaskContainer } from './TransformVisibilityTaskContainer'\nimport { useDomProxy } from './hooks/useDomProxy'\nimport { useInsideAttachment } from '../reality/context/InsideAttachmentContext'\nimport {\n useSpatialEvents,\n useSpatialEventsWhenSpatializedContainerExist,\n} from './hooks/useSpatialEvents'\nimport type { SpatializedMotionBinding } from './motion/motionBindingTypes'\n\n/**\n * Degraded fallback: strips spatial-only props and renders plain HTML.\n * This is a separate component so that SpatializedContainerBase never\n * has to conditionally skip its hooks.\n */\nfunction DegradedContainer<T extends SpatializedElementRef>({\n innerRef,\n ...inprops\n}: SpatializedContainerProps<T> & {\n innerRef: ForwardedRef<SpatializedElementRef<T>>\n}) {\n type DegradedProps = SpatializedContainerProps<T> & {\n 'enable-xr'?: unknown\n sizingMode?: unknown\n 'xr-animation'?: SpatializedMotionBinding\n }\n const {\n component: Component,\n children,\n ['enable-xr']: _enableXR,\n onSpatialTap: _onSpatialTap,\n onSpatialDragStart: _onSpatialDragStart,\n onSpatialDrag: _onSpatialDrag,\n onSpatialDragEnd: _onSpatialDragEnd,\n onSpatialRotate: _onSpatialRotate,\n onSpatialRotateEnd: _onSpatialRotateEnd,\n onSpatialMagnify: _onSpatialMagnify,\n onSpatialMagnifyEnd: _onSpatialMagnifyEnd,\n spatialEventOptions: _spatialEventOptions,\n spatializedContent: _content,\n createSpatializedElement: _create,\n getExtraSpatializedElementProperties: _getExtra,\n extraRefProps: _extraRef,\n sizingMode: _sizingMode,\n // `onSpatialContentReady` is destructured out (NOT spread to the DOM\n // element) so it never leaks as an attribute. Per the product-confirmed\n // semantics it fires ONLY when a real WebSpatial spatial content host\n // exists (the portal path via `useSpatialContentReady`); a degraded plain\n // HTML host has no such host, so the callback MUST NOT be invoked here —\n // this covers both the non-WebSpatial and attachment-degraded paths.\n onSpatialContentReady: _onSpatialContentReady,\n 'xr-animation': xrAnimation,\n ...restProps\n } = inprops as DegradedProps\n\n return (\n <Component ref={innerRef} {...restProps}>\n {children}\n </Component>\n )\n}\n\nexport function SpatializedContainerBase<T extends SpatializedElementRef>(\n inprops: SpatializedContainerProps<T>,\n ref: ForwardedRef<SpatializedElementRef<T>>,\n) {\n const isWebSpatialEnv = getSession() !== null\n const insideAttachment = useInsideAttachment()\n\n if (!isWebSpatialEnv || insideAttachment) {\n if (insideAttachment) {\n console.warn(\n `[WebSpatial] ${inprops.component || 'Spatial element'} cannot be used inside AttachmentAsset. Rendering as plain HTML.`,\n )\n }\n return <DegradedContainer {...inprops} innerRef={ref} />\n }\n\n const layer = useContext(SpatialLayerContext) + 1\n const rootSpatializedContainerObject = useContext(\n SpatializedContainerContext,\n ) as unknown as SpatializedContainerObject<T>\n const inSpatializedContainer = !!rootSpatializedContainerObject\n const portalInstanceObject = useContext(PortalInstanceContext)\n const inPortalInstanceEnv = !!portalInstanceObject\n const isInStandardInstance = !inPortalInstanceEnv\n\n const spatialId = useMemo(() => {\n return !inSpatializedContainer\n ? `root_container`\n : rootSpatializedContainerObject.getSpatialId(layer, isInStandardInstance)\n }, [])\n const spatialIdProps = {\n [SpatialID]: spatialId,\n }\n const {\n onSpatialTap,\n onSpatialDragStart,\n onSpatialDrag,\n onSpatialDragEnd,\n onSpatialRotate,\n onSpatialRotateEnd,\n onSpatialMagnify,\n onSpatialMagnifyEnd,\n extraRefProps,\n ...props\n } = inprops\n\n if (inSpatializedContainer) {\n if (inPortalInstanceEnv) {\n const spatialEvents = useSpatialEventsWhenSpatializedContainerExist<T>(\n {\n onSpatialTap,\n onSpatialDragStart,\n onSpatialDrag,\n onSpatialDragEnd,\n onSpatialRotate,\n onSpatialRotateEnd,\n onSpatialMagnify,\n onSpatialMagnifyEnd,\n },\n spatialId,\n rootSpatializedContainerObject,\n )\n\n // nested in another PortalSpatializedContainer\n return (\n <SpatialLayerContext.Provider value={layer}>\n <PortalSpatializedContainer<T>\n {...spatialIdProps}\n {...props}\n {...spatialEvents}\n />\n </SpatialLayerContext.Provider>\n )\n } else {\n // in standard instance env\n const {\n transformVisibilityTaskContainerCallback,\n standardSpatializedContainerCallback,\n spatialContainerRefProxy,\n } = useDomProxy<T>(ref, extraRefProps)\n\n const [probeClassName, setProbeClassName] = useState(\n () => props.className ?? '',\n )\n const notifyProbeClass = useCallback((name: string) => {\n setProbeClassName(prev => (prev === name ? prev : name))\n }, [])\n useEffect(() => {\n spatialContainerRefProxy.current.setMirrorClassNotify?.(\n notifyProbeClass,\n )\n return () => {\n spatialContainerRefProxy.current.setMirrorClassNotify?.(null)\n }\n }, [spatialContainerRefProxy, notifyProbeClass])\n\n useEffect(() => {\n rootSpatializedContainerObject.updateSpatialContainerRefProxyInfo(\n spatialId,\n spatialContainerRefProxy.current,\n )\n }, [spatialContainerRefProxy.current])\n\n const {\n spatializedContent,\n createSpatializedElement,\n getExtraSpatializedElementProperties,\n 'xr-animation': _xrAnimation,\n spatialEventOptions: _nestedSpatialEventOptions,\n onSpatialContentReady: _nestedOnSpatialContentReady,\n ...restProps\n } = props\n void _xrAnimation\n return (\n <SpatialLayerContext.Provider value={layer}>\n <StandardSpatializedContainer<T>\n ref={standardSpatializedContainerCallback}\n {...spatialIdProps}\n {...restProps}\n inStandardSpatializedContainer={true}\n />\n <TransformVisibilityTaskContainer\n ref={transformVisibilityTaskContainerCallback}\n {...spatialIdProps}\n component={props.component}\n className={probeClassName}\n style={props.style}\n />\n </SpatialLayerContext.Provider>\n )\n }\n } else {\n const {\n transformVisibilityTaskContainerCallback,\n standardSpatializedContainerCallback,\n spatialContainerRefProxy,\n } = useDomProxy<T>(ref, extraRefProps)\n\n const [probeClassName, setProbeClassName] = useState(\n () => props.className ?? '',\n )\n const notifyProbeClass = useCallback((name: string) => {\n setProbeClassName(prev => (prev === name ? prev : name))\n }, [])\n useEffect(() => {\n spatialContainerRefProxy.current.setMirrorClassNotify?.(notifyProbeClass)\n return () => {\n spatialContainerRefProxy.current.setMirrorClassNotify?.(null)\n }\n }, [spatialContainerRefProxy, notifyProbeClass])\n\n const spatialEvents = useSpatialEvents<T>(\n {\n onSpatialTap,\n onSpatialDragStart,\n onSpatialDrag,\n onSpatialDragEnd,\n onSpatialRotate,\n onSpatialRotateEnd,\n onSpatialMagnify,\n onSpatialMagnifyEnd,\n },\n spatialContainerRefProxy,\n )\n\n // This is the root spatialized container\n const spatializedContainerObject = useMemo(\n () => new SpatializedContainerObject(),\n [],\n )\n const {\n spatializedContent,\n createSpatializedElement,\n getExtraSpatializedElementProperties,\n 'xr-animation': _xrAnimation,\n spatialEventOptions: _rootSpatialEventOptions,\n onSpatialContentReady: _rootOnSpatialContentReady,\n ...restProps\n } = props\n void _xrAnimation\n\n return (\n <SpatialLayerContext.Provider value={layer}>\n <SpatializedContainerContext.Provider\n value={spatializedContainerObject}\n >\n <StandardSpatializedContainer<T>\n ref={standardSpatializedContainerCallback}\n {...spatialIdProps}\n {...restProps}\n inStandardSpatializedContainer={false}\n />\n <PortalSpatializedContainer<T>\n {...spatialIdProps}\n {...props}\n {...spatialEvents}\n />\n <TransformVisibilityTaskContainer\n ref={transformVisibilityTaskContainerCallback}\n {...spatialIdProps}\n component={props.component}\n className={probeClassName}\n style={props.style}\n />\n </SpatializedContainerContext.Provider>\n </SpatialLayerContext.Provider>\n )\n }\n}\n\n// No `withSSRSupported` wrapper: on the default entry this container is reached\n// only via the facade HOC delegate (`facades/withSpatialized2DElementContainer`)\n// once `useSpatialReady()` is ready — i.e. as a fresh client mount AFTER\n// hydration commits, never during the SSR or hydration pass. The eager entry is\n// CSR-only for spatial primitives (see `spatial-lazy-load` spec \"Entry\n// routing\"); SSR safety in mixed eager setups is the consumer's responsibility.\nexport const SpatializedContainer = forwardRef(SpatializedContainerBase) as <\n T extends SpatializedElementRef,\n>(\n props: SpatializedContainerProps<T> & {\n ref?: ForwardedRef<SpatializedElementRef<T>>\n },\n) => React.ReactElement | null\n","import { isSSREnv, Spatial, SpatialSession } from '@webspatial/core-sdk'\n// Create the default Spatial session for the app\nlet spatial: Spatial | null = null\nlet _currentSession: SpatialSession | null = null\n/** @hidden */\nexport function getSession() {\n if (isSSREnv()) return null\n if (!spatial) {\n spatial = new Spatial()\n }\n if (!spatial.isSupported()) {\n return null\n }\n if (_currentSession) {\n return _currentSession\n }\n _currentSession = spatial.requestSession()\n return _currentSession\n}\n\nexport { spatial }\n","import { createContext } from 'react'\n\n// SpatialLayerContext is used to mark the spatial layer of the spatial div, which is used to help portal instance find the correct layer standard instance div.\nexport const SpatialLayerContext = createContext(0)\n","import { useMemo, useContext, useEffect } from 'react'\nimport {\n PortalInstanceObject,\n PortalInstanceContext,\n} from './context/PortalInstanceContext'\nimport {\n PortalSpatializedContainerProps,\n SpatialContentReadyCallback,\n SpatialEventOptions,\n SpatializedElementRef,\n Vec3,\n} from './types'\n\nfunction constrainedAxisToVec3(\n input: SpatialEventOptions['constrainedToAxis'] | undefined,\n): Vec3 {\n if (input == null) return { x: 0, y: 0, z: 0 }\n if (Array.isArray(input)) {\n return { x: input[0] ?? 0, y: input[1] ?? 0, z: input[2] ?? 0 }\n }\n const v = input as Vec3\n return { x: v.x, y: v.y, z: v.z }\n}\n\nfunction constrainedAxisKey(\n input: SpatialEventOptions['constrainedToAxis'] | undefined,\n): string {\n const v = constrainedAxisToVec3(input)\n return `${v.x},${v.y},${v.z}`\n}\n\nimport { SpatialID } from './SpatialID'\nimport { useSync2DFrame } from './hooks/useSync2DFrame'\nimport { useSpatializedElement } from './hooks/useSpatializedElement'\nimport { useBindSpatializedMotion } from './motion/useBindSpatializedMotion'\nimport {\n SpatializedContainerContext,\n SpatializedContainerObject,\n} from './context/SpatializedContainerContext'\n\nfunction renderPlaceholderInSubPortal(\n portalInstanceObject: PortalInstanceObject,\n El: React.ElementType,\n) {\n const spatialId = portalInstanceObject.spatialId\n const inPortalInstanceEnv = !!portalInstanceObject.parentPortalInstanceObject\n const position =\n portalInstanceObject.computedStyle?.getPropertyValue('position')\n\n const shouldRenderPlaceHolder =\n inPortalInstanceEnv &&\n portalInstanceObject &&\n portalInstanceObject.domRect &&\n position !== 'absolute' &&\n position !== 'fixed'\n\n if (!shouldRenderPlaceHolder) {\n return <></>\n }\n\n const { width, height } = portalInstanceObject.domRect\n const display =\n portalInstanceObject.computedStyle!.getPropertyValue('display')\n\n const spatialIdProps = { [SpatialID]: spatialId }\n return (\n <El\n {...spatialIdProps}\n style={{\n position: 'relative',\n width: `${width}px`,\n height: `${height}px`,\n visibility: 'hidden',\n display,\n }}\n />\n )\n}\n\nexport function PortalSpatializedContainer<T extends SpatializedElementRef>(\n props: PortalSpatializedContainerProps<T> & {\n /** Forwarded to 2D `SpatializedContent` only (SpatialDiv). Ignored elsewhere. */\n onSpatialContentReady?: SpatialContentReadyCallback\n },\n) {\n const {\n spatializedContent: Content,\n createSpatializedElement,\n getExtraSpatializedElementProperties,\n 'xr-animation': xrAnimation,\n onSpatialTap,\n onSpatialDragStart,\n onSpatialDrag,\n onSpatialDragEnd,\n onSpatialRotate,\n onSpatialRotateEnd,\n onSpatialMagnify,\n onSpatialMagnifyEnd,\n spatialEventOptions,\n [SpatialID]: spatialId,\n ...restProps\n } = props\n\n const spatializedContainerObject: SpatializedContainerObject = useContext(\n SpatializedContainerContext,\n )!\n\n const parentPortalInstanceObject = useContext(PortalInstanceContext)\n const portalInstanceObject = useMemo(\n () =>\n new PortalInstanceObject(\n spatialId,\n spatializedContainerObject,\n parentPortalInstanceObject,\n getExtraSpatializedElementProperties,\n ),\n [],\n )\n useEffect(() => {\n portalInstanceObject.init()\n return () => {\n portalInstanceObject.destroy()\n }\n }, [])\n\n const spatializedElement = useSpatializedElement(\n createSpatializedElement,\n portalInstanceObject,\n )\n\n useSync2DFrame(\n spatialId,\n portalInstanceObject,\n spatializedContainerObject,\n spatializedElement,\n )\n\n useBindSpatializedMotion({\n binding: xrAnimation,\n element: spatializedElement,\n })\n\n const PlaceholderEl = renderPlaceholderInSubPortal(\n portalInstanceObject,\n props.component,\n )\n\n useEffect(() => {\n if (spatializedElement) {\n // @ts-ignore\n spatializedElement.onSpatialTap = onSpatialTap\n }\n }, [spatializedElement, onSpatialTap])\n\n useEffect(() => {\n if (spatializedElement) {\n // @ts-ignore\n spatializedElement.onSpatialDrag = onSpatialDrag\n }\n }, [spatializedElement, onSpatialDrag])\n\n useEffect(() => {\n if (spatializedElement) {\n // @ts-ignore\n spatializedElement.onSpatialDragEnd = onSpatialDragEnd\n }\n }, [spatializedElement, onSpatialDragEnd])\n\n useEffect(() => {\n if (spatializedElement) {\n // @ts-ignore\n spatializedElement.onSpatialRotate = onSpatialRotate\n }\n }, [spatializedElement, onSpatialRotate])\n\n useEffect(() => {\n if (spatializedElement) {\n // @ts-ignore\n spatializedElement.onSpatialRotateEnd = onSpatialRotateEnd\n }\n }, [spatializedElement, onSpatialRotateEnd])\n\n useEffect(() => {\n if (spatializedElement) {\n // @ts-ignore\n spatializedElement.onSpatialMagnify = onSpatialMagnify\n }\n }, [spatializedElement, onSpatialMagnify])\n\n useEffect(() => {\n if (spatializedElement) {\n // @ts-ignore\n spatializedElement.onSpatialMagnifyEnd = onSpatialMagnifyEnd\n }\n }, [spatializedElement, onSpatialMagnifyEnd])\n\n useEffect(() => {\n if (spatializedElement) {\n // @ts-ignore\n spatializedElement.onSpatialDragStart = onSpatialDragStart\n }\n }, [spatializedElement, onSpatialDragStart])\n\n const rotateConstraintKey = constrainedAxisKey(\n spatialEventOptions?.constrainedToAxis,\n )\n\n useEffect(() => {\n if (!spatializedElement) return\n const axis = constrainedAxisToVec3(spatialEventOptions?.constrainedToAxis)\n void spatializedElement.updateProperties({ rotateConstrainedToAxis: axis })\n }, [spatializedElement, rotateConstraintKey])\n\n return (\n <PortalInstanceContext.Provider value={portalInstanceObject}>\n {spatializedElement && (\n <Content\n spatializedElement={spatializedElement}\n portalInstanceObject={portalInstanceObject}\n {...restProps}\n />\n )}\n {PlaceholderEl}\n </PortalInstanceContext.Provider>\n )\n}\n","import { Spatialized2DElement, SpatializedElement } from '@webspatial/core-sdk'\nimport { createContext } from 'react'\nimport { SpatializedContainerObject } from './SpatializedContainerContext'\nimport { parseTransformOrigin } from '../utils'\nimport { SpatialCustomStyleVars, SpatialTransformVisibility } from '../types'\nimport { getSession } from '../../utils'\n\ntype DomRect = {\n x: number\n y: number\n width: number\n height: number\n}\n\ntype CachedDomInfo = {\n // point to 2DFrame dom in StandardInstanceContainer\n dom: HTMLElement\n computedStyle: CSSStyleDeclaration\n isFixedPosition: boolean\n}\n\ntype CachedTransformVisibilityInfo = {\n visibility: string\n transformMatrix: DOMMatrix\n}\n\nexport class PortalInstanceObject {\n readonly spatialId: string\n readonly spatializedContainerObject: SpatializedContainerObject\n readonly parentPortalInstanceObject: PortalInstanceObject | null\n spatializedElement?: SpatializedElement\n\n // cachedDomInfo used for cache dom info\n // when dom is updated, this property should be updated as well\n private cachedDomInfo?: CachedDomInfo\n\n get dom(): HTMLElement | undefined {\n return this.cachedDomInfo?.dom\n }\n\n get computedStyle(): CSSStyleDeclaration | undefined {\n return this.cachedDomInfo?.computedStyle\n }\n\n get isFixedPosition(): boolean | undefined {\n return this.cachedDomInfo?.isFixedPosition\n }\n\n // cachedDomRect used for cache dom rect\n private cachedDomRect?: DomRect\n get domRect(): DomRect | undefined {\n return this.cachedDomRect\n }\n\n // cachedTransformVisibilityInfo used for cache transform visibility info\n private cachedTransformVisibilityInfo?: CachedTransformVisibilityInfo\n get transformMatrix() {\n return this.cachedTransformVisibilityInfo?.transformMatrix\n }\n get visibility() {\n return this.cachedTransformVisibilityInfo?.visibility\n }\n\n // spatializedElementPromise used for get spatialized element\n // SpatializedElement is when attachSpatializedElement is called\n private spatializedElementPromise?: Promise<SpatializedElement>\n private spatializedElementResolver?: (\n spatializedElement: SpatializedElement,\n ) => void\n\n // used for get extra spatialized element properties\n private getExtraSpatializedElementProperties?: (\n computedStyle: CSSStyleDeclaration,\n ) => Record<string, string | number>\n\n constructor(\n spatialId: string,\n spatializedContainerObject: SpatializedContainerObject,\n parentPortalInstanceObject: PortalInstanceObject | null,\n getExtraSpatializedElementProperties?: (\n computedStyle: CSSStyleDeclaration,\n ) => Record<string, string>,\n ) {\n this.spatialId = spatialId\n this.spatializedContainerObject = spatializedContainerObject\n this.parentPortalInstanceObject = parentPortalInstanceObject\n this.getExtraSpatializedElementProperties =\n getExtraSpatializedElementProperties\n\n this.spatializedElementPromise = new Promise<SpatializedElement>(\n resolve => {\n this.spatializedElementResolver = resolve\n },\n )\n }\n\n // called when PortalSpatializedContainer is mounted\n init() {\n this.spatializedContainerObject.onSpatialTransformVisibilityChange(\n this.spatialId,\n this.onSpatialTransformVisibilityChange,\n )\n }\n\n // called when PortalSpatializedContainer is unmounted\n destroy() {\n this.spatializedContainerObject.offSpatialTransformVisibilityChange(\n this.spatialId,\n this.onSpatialTransformVisibilityChange,\n )\n }\n\n private onSpatialTransformVisibilityChange = (\n spatialTransform: SpatialTransformVisibility,\n ) => {\n this.cachedTransformVisibilityInfo = {\n transformMatrix: new DOMMatrix(spatialTransform.transform),\n visibility: spatialTransform.visibility,\n }\n this.updateSpatializedElementProperties()\n }\n\n // called when 2D frame change\n notify2DFrameChange() {\n const dom = this.spatializedContainerObject.querySpatialDomBySpatialId(\n this.spatialId,\n )\n if (!dom) {\n return\n }\n const computedStyle = getComputedStyle(dom)\n this.cachedDomInfo = {\n dom,\n computedStyle,\n isFixedPosition: computedStyle.getPropertyValue('position') === 'fixed',\n }\n\n this.updateSpatializedElementProperties()\n\n const __innerSpatializedElement = () => this.spatializedElement\n\n Object.assign(dom, {\n __innerSpatializedElement,\n })\n }\n\n private async getSpatializedElement() {\n return this.spatializedElementPromise\n }\n\n // called when SpatializedElement is created\n attachSpatializedElement(spatializedElement: SpatializedElement) {\n this.spatializedElement = spatializedElement\n // attach to spatializedContainerObject\n this.addToParent(spatializedElement)\n this.spatializedElementResolver?.(spatializedElement)\n\n this.updateSpatializedElementProperties()\n }\n\n private inAddingToParent: boolean = false\n\n private async addToParent(spatializedElement: SpatializedElement) {\n if (this.inAddingToParent) {\n return\n }\n this.inAddingToParent = true\n\n if (this.isFixedPosition || !this.parentPortalInstanceObject) {\n // Add as a child of the current page\n var spatialScene = await getSession()!.getSpatialScene()\n await spatialScene.addSpatializedElement(spatializedElement!)\n } else {\n const parentSpatialized2DElement =\n (await this.parentPortalInstanceObject.getSpatializedElement()) as Spatialized2DElement\n // Add as a child of the parent\n parentSpatialized2DElement.addSpatializedElement(spatializedElement!)\n }\n this.inAddingToParent = false\n }\n\n private updateSpatializedElementProperties() {\n // console.log('updateSpatializedElement', this.spatializedElement)\n // read from spatializedContainerContext\n const dom = this.dom\n const spatializedElement = this.spatializedElement\n const visibility = this.visibility\n if (!dom || !spatializedElement || !visibility || !this.transformMatrix) {\n // console.log(\n // `not ready to updateSpatializedElementProperties! dom is ${!!dom} spatializedElement is ${spatializedElement} visibility is ${visibility}`,\n // )\n return\n }\n\n const computedStyle = this.computedStyle!\n const isFixedPosition = this.isFixedPosition!\n\n let domRect = dom.getBoundingClientRect()\n\n let { x, y } = domRect\n if (!isFixedPosition) {\n const parentDom =\n this.spatializedContainerObject.queryParentSpatialDomBySpatialId(\n this.spatialId,\n )\n if (parentDom) {\n const parentDomRect = parentDom.getBoundingClientRect()\n x -= parentDomRect.x\n y -= parentDomRect.y\n } else {\n // Adjust to get the page relative to document instead of viewport\n x += window.scrollX\n y += window.scrollY\n }\n }\n\n // update cachedDomRect\n this.cachedDomRect = {\n x: domRect.x,\n y: domRect.y,\n width: domRect.width,\n height: domRect.height,\n }\n\n // console.log('updateSpatializedElementProperties', domRect)\n\n const width = domRect.width\n const height = domRect.height\n const opacity = parseFloat(computedStyle.getPropertyValue('opacity'))\n const scrollWithParent = !isFixedPosition\n\n const display = computedStyle.getPropertyValue('display')\n const visible = visibility === 'visible' && display !== 'none'\n\n const zIndex =\n parseFloat(\n computedStyle.getPropertyValue(SpatialCustomStyleVars.xrZIndex),\n ) || 0\n const backOffset =\n parseFloat(computedStyle.getPropertyValue(SpatialCustomStyleVars.back)) ||\n 0\n\n const depth =\n parseFloat(\n computedStyle.getPropertyValue(SpatialCustomStyleVars.depth),\n ) || 0\n\n const rotationAnchor = parseTransformOrigin(computedStyle)\n const extraProperties =\n this.getExtraSpatializedElementProperties?.(computedStyle) || {}\n\n spatializedElement.updateProperties({\n clientX: x,\n clientY: y,\n width,\n height,\n depth,\n opacity,\n scrollWithParent,\n zIndex,\n visible,\n backOffset,\n rotationAnchor,\n ...extraProperties,\n })\n\n // update transform\n spatializedElement.updateTransform(this.transformMatrix!)\n\n // assign spatializedElement to dom\n Object.assign(this.dom, {\n __spatializedElement: spatializedElement,\n })\n }\n}\n\nexport const PortalInstanceContext = createContext<PortalInstanceObject | null>(\n null,\n)\n","import { CSSProperties } from 'react'\n\nexport function getInheritedStyleProps(\n computedStyle: CSSStyleDeclaration,\n): CSSProperties {\n //https://stackoverflow.com/questions/5612302/which-css-properties-are-inherited\n var propNames: (keyof CSSProperties)[] = [\n 'borderCollapse',\n 'borderSpacing',\n 'captionSide',\n 'color',\n 'cursor',\n 'direction',\n // 'elevation',\n 'emptyCells',\n 'fontFamily',\n 'fontSize',\n 'fontStyle',\n 'fontVariant',\n 'fontWeight',\n 'font',\n 'letterSpacing',\n 'lineHeight',\n 'listStyleImage',\n 'listStylePosition',\n 'listStyleType',\n 'listStyle',\n 'orphans',\n // 'pitchRange',\n // 'pitch',\n 'quotes',\n // 'richness',\n // 'speakHeader',\n // 'speakNumeral',\n // 'speakPunctuation',\n // 'speak',\n // 'speechRate',\n // 'stress',\n 'textAlign',\n 'textIndent',\n 'textTransform',\n 'visibility',\n // 'voiceFamily',\n // 'volume',\n 'whiteSpace',\n 'widows',\n 'wordSpacing',\n // background also need to be synced\n 'background',\n // position also need to be synced\n 'position',\n\n 'width',\n 'height',\n\n 'display',\n\n // content-visibility also need to be synced\n 'contentVisibility',\n ]\n var props: CSSProperties = {}\n for (var cssName of propNames) {\n if ((computedStyle as any)[cssName]) {\n props[cssName] = (computedStyle as any)[cssName]\n }\n }\n return props\n}\n\nexport function parseTransformOrigin(computedStyle: CSSStyleDeclaration) {\n const transformOriginProperty =\n computedStyle.getPropertyValue('transform-origin')\n const [x, y] = transformOriginProperty.split(' ').map(parseFloat)\n const width = parseFloat(computedStyle.getPropertyValue('width'))\n const height = parseFloat(computedStyle.getPropertyValue('height'))\n\n return {\n x: width > 0 ? x / width : 0.5,\n y: height > 0 ? y / height : 0.5,\n z: 0.5,\n }\n}\n\nfunction parseBorderRadius(borderProperty: string, width: number) {\n if (borderProperty === '') {\n return 0\n }\n if (borderProperty.endsWith('%')) {\n return (width * parseFloat(borderProperty)) / 100\n }\n return parseFloat(borderProperty)\n}\n\nexport function parseCornerRadius(computedStyle: CSSStyleDeclaration) {\n const width = parseFloat(computedStyle.getPropertyValue('width'))\n\n const topLeftPropertyValue = computedStyle.getPropertyValue(\n 'border-top-left-radius',\n )\n const topRightPropertyValue = computedStyle.getPropertyValue(\n 'border-top-right-radius',\n )\n const bottomLeftPropertyValue = computedStyle.getPropertyValue(\n 'border-bottom-left-radius',\n )\n const bottomRightPropertyValue = computedStyle.getPropertyValue(\n 'border-bottom-right-radius',\n )\n\n const cornerRadius = {\n topLeading: parseBorderRadius(topLeftPropertyValue, width),\n bottomLeading: parseBorderRadius(bottomLeftPropertyValue, width),\n topTrailing: parseBorderRadius(topRightPropertyValue, width),\n bottomTrailing: parseBorderRadius(bottomRightPropertyValue, width),\n }\n\n return cornerRadius\n}\n\nexport function extractAndRemoveCustomProperties(\n cssText: string,\n properties: string[],\n) {\n if (!cssText) {\n return { extractedValues: {}, filteredCssText: '' }\n }\n\n const extractedValues: Record<string, string> = {}\n const rules = cssText.split(';')\n\n const filteredRules = rules.filter(rule => {\n const [key, value] = rule.split(':').map(part => part.trim())\n if (properties.includes(key)) {\n extractedValues[key] = value\n return false\n }\n return true\n })\n\n const filteredCssText = filteredRules.join(';').trim()\n return { extractedValues, filteredCssText }\n}\n\nexport function splitCSSText(cssText: string) {\n const rules = cssText.split(';')\n const filteredRules = rules.filter(rule => rule.trim() !== '')\n return filteredRules\n}\n\nexport function joinToCSSText(cssKV: Record<string, string>) {\n const rules = Object.entries(cssKV).map(([key, value]) => `${key}: ${value}`)\n return rules.join(';')\n}\n","import React, { ElementType } from 'react'\nimport type { PortalInstanceObject } from './context/PortalInstanceContext'\nimport type { SpatializedMotionBinding } from './motion/motionBindingTypes'\nimport { SpatialID } from './SpatialID'\nimport {\n ModelLoadingMode,\n SpatializedElement,\n SpatialTapEvent as CoreSpatialTapEvent,\n SpatialDragEvent as CoreSpatialDragEvent,\n SpatialDragStartEvent as CoreSpatialDragStartEvent,\n SpatialDragEndEvent as CoreSpatialDragEndEvent,\n SpatialRotateEvent as CoreSpatialRotateEvent,\n SpatialRotateEndEvent as CoreSpatialRotateEndEvent,\n SpatialMagnifyEvent as CoreSpatialMagnifyEvent,\n SpatialMagnifyEndEvent as CoreSpatialMagnifyEndEvent,\n SpatializedStatic3DElement,\n type StageMode,\n type Vec3,\n} from '@webspatial/core-sdk'\n\nexport type { Point3D, Vec3 } from '@webspatial/core-sdk'\nexport type { Quaternion } from '@webspatial/core-sdk'\n\n/** Connected content root for imperative mounting (portal root or web fallback host). */\nexport type SpatialContentReadyContext = {\n host: HTMLElement\n}\n\nexport type SpatialContentReadyCallback = (\n ctx: SpatialContentReadyContext,\n) => void | (() => void)\n\n/** Options for spatial pointer/gesture behavior (not DOM attributes). */\nexport type SpatialEventOptions = {\n /**\n * Direction vector for rotate gesture constraint. `[0, 0, 0]` or omit = unconstrained.\n */\n constrainedToAxis?: Vec3 | readonly [number, number, number]\n}\n\n// SpatialEvents\ntype SpatialEventProps<T extends SpatializedElementRef> = {\n onSpatialTap?: (event: SpatialTapEvent<T>) => void\n onSpatialDragStart?: (event: SpatialDragStartEvent<T>) => void\n onSpatialDrag?: (event: SpatialDragEvent<T>) => void\n onSpatialDragEnd?: (event: SpatialDragEndEvent<T>) => void\n onSpatialRotate?: (event: SpatialRotateEvent<T>) => void\n onSpatialRotateEnd?: (event: SpatialRotateEndEvent<T>) => void\n onSpatialMagnify?: (event: SpatialMagnifyEvent<T>) => void\n onSpatialMagnifyEnd?: (event: SpatialMagnifyEndEvent<T>) => void\n}\n\nexport interface StandardSpatializedContainerProps\n extends React.ComponentPropsWithoutRef<'div'> {\n component: ElementType\n inStandardSpatializedContainer?: boolean\n [SpatialID]: string\n}\n\nexport type PortalSpatializedContainerProps<T extends SpatializedElementRef> =\n SpatialEventProps<T> &\n React.ComponentPropsWithoutRef<'div'> & {\n component: ElementType\n spatializedContent: ElementType\n createSpatializedElement: () => Promise<SpatializedElement>\n getExtraSpatializedElementProperties?: (\n computedStyle: CSSStyleDeclaration,\n ) => Record<string, any>\n spatialEventOptions?: SpatialEventOptions\n 'xr-animation'?: SpatializedMotionBinding\n\n [SpatialID]: string\n }\n\nexport type SpatializedContainerProps<T extends SpatializedElementRef> = Omit<\n StandardSpatializedContainerProps & PortalSpatializedContainerProps<T>,\n typeof SpatialID | 'onLoad' | 'onError'\n> & {\n extraRefProps?: (domProxy: T) => Record<string, unknown>\n /**\n * SpatialDiv only — fired when `ctx.host` is connected (portal root or web fallback host).\n * Not part of `Model` / `Reality` public APIs.\n */\n onSpatialContentReady?: SpatialContentReadyCallback\n}\n\nexport type SpatializedContentProps<\n T extends SpatializedElementRef,\n P extends ElementType,\n> = Omit<PortalSpatializedContainerProps<T>, 'spatializedContent'> & {\n spatializedElement: SpatializedElement\n portalInstanceObject: PortalInstanceObject\n /** SpatialDiv (2D) portal content only. */\n onSpatialContentReady?: SpatialContentReadyCallback\n}\n\nexport type Spatialized2DElementContainerProps<P extends ElementType> =\n SpatialEventProps<SpatializedElementRef> &\n React.ComponentPropsWithRef<'div'> & {\n component: P\n spatialEventOptions?: SpatialEventOptions\n onSpatialContentReady?: SpatialContentReadyCallback\n }\n\nexport type SpatializedStatic3DContainerProps =\n SpatialEventProps<SpatializedStatic3DElementRef> &\n Omit<React.ComponentPropsWithoutRef<'div'>, 'onLoad' | 'onError'> & {\n src?: string\n poster?: string\n autoPlay?: boolean\n loop?: boolean\n loading?: ModelLoadingMode\n stagemode?: StageMode\n children?: React.ReactNode\n onLoad?: (event: ModelLoadEvent) => void\n onError?: (event: ModelLoadEvent) => void\n spatialEventOptions?: SpatialEventOptions\n /** Native root-transform motion binding from `useAnimation()` via `xr-animation`. */\n 'xr-animation'?: SpatializedMotionBinding\n }\n\nexport type SpatializedStatic3DContentProps = {\n spatializedElement: SpatializedStatic3DElement\n src?: string\n poster?: string\n autoPlay?: boolean\n loop?: boolean\n loading?: ModelLoadingMode\n stagemode?: StageMode\n children?: React.ReactNode\n onLoad?: (event: ModelLoadEvent) => void\n onError?: (event: ModelLoadEvent) => void\n 'xr-animation'?: SpatializedMotionBinding\n}\n\nexport const SpatialCustomStyleVars = {\n back: '--xr-back',\n depth: '--xr-depth',\n backgroundMaterial: '--xr-background-material',\n xrZIndex: '--xr-z-index',\n}\n\nexport interface SpatialTransformVisibility {\n transform: string\n visibility: string\n}\n\nexport type SpatializedElementRef<T extends HTMLElement = HTMLElement> = T\n\nexport type SpatializedDivElementRef = SpatializedElementRef<HTMLDivElement>\n\nexport type SpatializedStatic3DElementRef = SpatializedDivElementRef & {\n currentSrc: string\n ready: Promise<ModelLoadEvent>\n entityTransform: DOMMatrixReadOnly\n play(): Promise<void>\n pause(): Promise<void>\n readonly paused: boolean\n readonly duration: number\n playbackRate: number\n currentTime: number\n}\n\ntype CurrentTarget<T extends SpatializedElementRef> = {\n currentTarget: T\n}\n\nexport type SpatialTapEvent<\n T extends SpatializedElementRef = SpatializedElementRef,\n> = CoreSpatialTapEvent &\n CurrentTarget<T> & {\n readonly offsetX: number\n readonly offsetY: number\n readonly offsetZ: number\n readonly clientX: number\n readonly clientY: number\n readonly clientZ: number\n }\n\nexport type SpatialDragStartEvent<\n T extends SpatializedElementRef = SpatializedElementRef,\n> = CoreSpatialDragStartEvent &\n CurrentTarget<T> & {\n readonly offsetX: number\n readonly offsetY: number\n readonly offsetZ: number\n readonly clientX: number\n readonly clientY: number\n readonly clientZ: number\n }\n\nexport type SpatialDragEvent<\n T extends SpatializedElementRef = SpatializedElementRef,\n> = CoreSpatialDragEvent &\n CurrentTarget<T> & {\n readonly translationX: number\n readonly translationY: number\n readonly translationZ: number\n }\n\nexport type SpatialDragEndEvent<\n T extends SpatializedElementRef = SpatializedElementRef,\n> = CoreSpatialDragEndEvent & CurrentTarget<T>\n\nexport type SpatialRotateEvent<\n T extends SpatializedElementRef = SpatializedElementRef,\n> = CoreSpatialRotateEvent &\n CurrentTarget<T> & {\n readonly quaternion: import('@webspatial/core-sdk').Quaternion\n }\n\nexport type SpatialRotateEndEvent<\n T extends SpatializedElementRef = SpatializedElementRef,\n> = CoreSpatialRotateEndEvent & CurrentTarget<T>\n\nexport type SpatialMagnifyEvent<\n T extends SpatializedElementRef = SpatializedElementRef,\n> = CoreSpatialMagnifyEvent &\n CurrentTarget<T> & {\n readonly magnification: number\n }\n\nexport type SpatialMagnifyEndEvent<\n T extends SpatializedElementRef = SpatializedElementRef,\n> = CoreSpatialMagnifyEndEvent & CurrentTarget<T>\n\n// Model Spatial Event\nexport type ModelSpatialTapEvent =\n SpatialTapEvent<SpatializedStatic3DElementRef>\nexport type ModelSpatialDragStartEvent =\n SpatialDragStartEvent<SpatializedStatic3DElementRef>\nexport type ModelSpatialDragEvent =\n SpatialDragEvent<SpatializedStatic3DElementRef>\nexport type ModelSpatialDragEndEvent =\n SpatialDragEndEvent<SpatializedStatic3DElementRef>\nexport type ModelSpatialRotateEvent =\n SpatialRotateEvent<SpatializedStatic3DElementRef>\nexport type ModelSpatialRotateEndEvent =\n SpatialRotateEndEvent<SpatializedStatic3DElementRef>\nexport type ModelSpatialMagnifyEvent =\n SpatialMagnifyEvent<SpatializedStatic3DElementRef>\nexport type ModelSpatialMagnifyEndEvent =\n SpatialMagnifyEndEvent<SpatializedStatic3DElementRef>\n\nexport type ModelLoadEvent<T extends EventTarget = EventTarget> =\n CustomEvent & {\n target: T\n currentTarget: SpatializedStatic3DElementRef\n }\n","import { useCallback, useEffect, useLayoutEffect, useState } from 'react'\nimport type { SpatializedElement } from '@webspatial/core-sdk'\nimport { scheduleSyncParentHeadToChild } from '../../utils/windowStyleSync'\nimport { SpatializedContainerObject } from '../context/SpatializedContainerContext'\nimport { PortalInstanceObject } from '../context/PortalInstanceContext'\n\nfunction useForceUpdate() {\n const [, setToggle] = useState(false)\n return useCallback(() => setToggle(toggle => !toggle), [])\n}\n\nfunction getChildWindow(spatializedElement?: SpatializedElement) {\n return (\n spatializedElement as SpatializedElement & {\n windowProxy?: WindowProxy\n }\n )?.windowProxy\n}\n\nexport function useSync2DFrame(\n spatialId: string,\n portalInstanceObject: PortalInstanceObject,\n spatializedContainerObject: SpatializedContainerObject,\n spatializedElement?: SpatializedElement,\n) {\n const forceUpdate = useForceUpdate()\n const childWindow = getChildWindow(spatializedElement)\n\n const sync = useCallback(() => {\n portalInstanceObject.notify2DFrameChange()\n if (childWindow) {\n scheduleSyncParentHeadToChild(childWindow, 'afterHostLayout', () => {\n forceUpdate()\n })\n return\n }\n forceUpdate()\n }, [portalInstanceObject, childWindow, forceUpdate])\n\n useEffect(() => {\n spatializedContainerObject.on2DFrameChange(spatialId, sync)\n sync()\n\n return () => {\n spatializedContainerObject.off2DFrameChange(spatialId)\n }\n }, [spatialId, portalInstanceObject, spatializedContainerObject, sync])\n\n useLayoutEffect(() => {\n if (!spatializedElement) return\n portalInstanceObject.notify2DFrameChange()\n if (childWindow) {\n scheduleSyncParentHeadToChild(childWindow, 'afterHostLayout', () => {\n forceUpdate()\n })\n return\n }\n forceUpdate()\n }, [spatializedElement, childWindow, portalInstanceObject, forceUpdate])\n}\n","import { SpatialStyleInfoUpdateEvent } from '../notifyUpdateStandInstanceLayout'\n\nexport function asyncLoadStyleToChildWindow(\n childWindow: WindowProxy,\n link: HTMLLinkElement,\n isCurrent: () => boolean,\n): Promise<boolean> {\n return new Promise(resolve => {\n const { href } = link\n const sep = href.includes('?') ? '&' : '?'\n link.href = `${href}${sep}uniqueURL=${Math.random()}`\n\n let finished = false\n const finish = (ok: boolean) => {\n if (finished) return\n finished = true\n resolve(ok)\n }\n\n // need to wait for some time to make sure the style is loaded\n // otherwise, the style may not be applied\n link.onerror = () => {\n finish(false)\n }\n link.onload = () => {\n if (!isCurrent()) {\n link.parentNode?.removeChild(link)\n finish(false)\n return\n }\n finish(true)\n }\n\n setTimeout(() => {\n if (!isCurrent()) {\n finish(false)\n return\n }\n childWindow.document.head.appendChild(link)\n }, 50)\n })\n}\n\nconst WEBSPATIAL_SYNC_ATTR = 'data-webspatial-sync'\nconst WEBSPATIAL_SYNC_KEY_ATTR = 'data-webspatial-sync-key'\n\n/**\n * styled-components (and similar runtimes) often update CSS via CSSStyleSheet\n * insertRule/deleteRule without mutating the <style> node's text children.\n * cloneNode(true) would miss those live rules — serialize sheet.cssRules instead.\n */\nexport function getStyleElementTextForSync(styleEl: HTMLStyleElement): string {\n const sheet = styleEl.sheet\n if (sheet) {\n try {\n const parts: string[] = []\n for (let i = 0; i < sheet.cssRules.length; i++) {\n parts.push(sheet.cssRules[i]!.cssText)\n }\n if (parts.length > 0) return parts.join('\\n')\n } catch {\n // Inaccessible stylesheet (e.g. cross-origin) — fall back to DOM text.\n }\n }\n return styleEl.textContent ?? ''\n}\n\nfunction copyParentStyleAttributes(\n source: HTMLStyleElement,\n target: HTMLStyleElement,\n) {\n const sourceAttrNames = new Set(\n Array.from(source.attributes, attr => attr.name),\n )\n for (const attr of Array.from(target.attributes)) {\n if (attr.name === WEBSPATIAL_SYNC_ATTR) continue\n if (!sourceAttrNames.has(attr.name)) target.removeAttribute(attr.name)\n }\n\n for (const attr of Array.from(source.attributes)) {\n if (attr.name === WEBSPATIAL_SYNC_ATTR) continue\n target.setAttribute(attr.name, attr.value)\n }\n}\n\nexport function cloneParentStyleElementForSync(\n styleEl: HTMLStyleElement,\n): HTMLStyleElement {\n const node = document.createElement('style')\n copyParentStyleAttributes(styleEl, node)\n node.setAttribute(WEBSPATIAL_SYNC_ATTR, '1')\n return node\n}\n\nfunction getStyleSheetRuleTexts(styleEl: HTMLStyleElement): string[] | null {\n const sheet = styleEl.sheet\n if (!sheet) return null\n try {\n const texts: string[] = []\n for (let i = 0; i < sheet.cssRules.length; i++) {\n texts.push(sheet.cssRules[i]!.cssText)\n }\n return texts\n } catch {\n return null\n }\n}\n\nfunction clearStyleSheetRules(sheet: CSSStyleSheet) {\n while (sheet.cssRules.length > 0) {\n sheet.deleteRule(sheet.cssRules.length - 1)\n }\n}\n\nfunction getStyleTextForRules(\n source: HTMLStyleElement,\n parentRules?: string[] | null,\n) {\n if (parentRules && parentRules.length > 0) return parentRules.join('\\n')\n return source.textContent ?? ''\n}\n\nfunction applyFullTextStyleSync(\n target: HTMLStyleElement,\n source: HTMLStyleElement,\n text = getStyleElementTextForSync(source),\n) {\n const sheet = target.sheet\n if (sheet) {\n try {\n clearStyleSheetRules(sheet)\n } catch {\n // Fall through to textContent assignment.\n }\n }\n target.textContent = text\n}\n\n/**\n * Mirror parent CSSOM into an existing portal <style> via insertRule/deleteRule\n * so append-only CSS-in-JS updates do not replace the whole stylesheet text.\n */\nexport function syncStyleSheetRulesToChild(\n target: HTMLStyleElement,\n source: HTMLStyleElement,\n precomputedParentRules?: string[] | null,\n precomputedText?: string,\n) {\n const parentRules =\n precomputedParentRules === undefined\n ? getStyleSheetRuleTexts(source)\n : precomputedParentRules\n const parentText =\n precomputedText ?? getStyleTextForRules(source, parentRules)\n if (parentRules === null) {\n applyFullTextStyleSync(target, source, parentText)\n return\n }\n\n if (parentRules.length === 0) {\n const sheet = target.sheet\n if (sheet) {\n try {\n clearStyleSheetRules(sheet)\n } catch {\n applyFullTextStyleSync(target, source)\n return\n }\n }\n if (target.textContent !== parentText) target.textContent = parentText\n return\n }\n\n const sheet = target.sheet\n if (!sheet) {\n applyFullTextStyleSync(target, source, parentText)\n return\n }\n\n try {\n let commonPrefix = 0\n const maxPrefix = Math.min(sheet.cssRules.length, parentRules.length)\n while (commonPrefix < maxPrefix) {\n if (sheet.cssRules[commonPrefix]!.cssText !== parentRules[commonPrefix]) {\n break\n }\n commonPrefix++\n }\n\n while (sheet.cssRules.length > commonPrefix) {\n sheet.deleteRule(sheet.cssRules.length - 1)\n }\n\n for (let i = commonPrefix; i < parentRules.length; i++) {\n sheet.insertRule(parentRules[i]!, i)\n }\n } catch {\n applyFullTextStyleSync(target, source, parentText)\n }\n}\n\nexport type ParentHeadSnapshot = {\n parentStyles: HTMLStyleElement[]\n parentStylesheets: HTMLLinkElement[]\n documentElementClassName: string\n styleRuleTexts: Array<string[] | null>\n styleTextContents: string[]\n}\n\nexport function captureParentHeadSnapshot(): ParentHeadSnapshot {\n const parentStyles = Array.from(\n document.head.querySelectorAll('style'),\n ) as HTMLStyleElement[]\n const styleRuleTexts = parentStyles.map(getStyleSheetRuleTexts)\n const styleTextContents = parentStyles.map((style, index) =>\n getStyleTextForRules(style, styleRuleTexts[index]),\n )\n const parentStylesheets = Array.from(\n document.head.querySelectorAll('link[rel=\"stylesheet\"][href]'),\n ) as HTMLLinkElement[]\n\n return {\n parentStyles,\n parentStylesheets,\n documentElementClassName: document.documentElement.className,\n styleRuleTexts,\n styleTextContents,\n }\n}\n\n/** Update portal <style> nodes in place; prefer CSSOM rule deltas over full text replace. */\nfunction syncInlineStylesToChild(\n childHead: HTMLHeadElement,\n snapshot: ParentHeadSnapshot,\n) {\n const { parentStyles, styleRuleTexts, styleTextContents } = snapshot\n const existing = Array.from(\n childHead.querySelectorAll(`style[${WEBSPATIAL_SYNC_ATTR}=\"1\"]`),\n ) as HTMLStyleElement[]\n\n for (let i = 0; i < parentStyles.length; i++) {\n const source = parentStyles[i]!\n const target = existing[i]\n if (target) {\n copyParentStyleAttributes(source, target)\n syncStyleSheetRulesToChild(\n target,\n source,\n styleRuleTexts[i],\n styleTextContents[i],\n )\n } else {\n const node = cloneParentStyleElementForSync(source)\n childHead.appendChild(node)\n syncStyleSheetRulesToChild(\n node,\n source,\n styleRuleTexts[i],\n styleTextContents[i],\n )\n }\n }\n\n for (let i = parentStyles.length; i < existing.length; i++) {\n existing[i]!.parentNode?.removeChild(existing[i]!)\n }\n}\n\nexport function setOpenWindowStyle(openedWindow: WindowProxy) {\n openedWindow.document.documentElement.style.cssText +=\n document.documentElement.style.cssText\n openedWindow.document.documentElement.style.backgroundColor = 'transparent'\n openedWindow.document.body.style.margin = '0px'\n\n // openedWindow body's width and height should be set to inline-block to make sure the width and height are correct\n openedWindow.document.body.style.display = 'inline-block'\n openedWindow.document.body.style.minWidth = 'auto'\n openedWindow.document.body.style.minHeight = 'auto'\n openedWindow.document.body.style.maxWidth = 'fit-content'\n openedWindow.document.body.style.minWidth = 'fit-content'\n openedWindow.document.body.style.background = 'transparent'\n}\n\ninterface SyncController {\n version: number\n}\n\nconst controllers = new WeakMap<WindowProxy, SyncController>()\n\nfunction getController(childWindow: WindowProxy): SyncController {\n const prev = controllers.get(childWindow)\n if (prev) return prev\n const next: SyncController = { version: 0 }\n controllers.set(childWindow, next)\n return next\n}\n\nexport async function syncParentHeadToChild(\n childWindow: WindowProxy,\n snapshot = captureParentHeadSnapshot(),\n) {\n const controller = getController(childWindow)\n const version = ++controller.version\n const styleLoadedPromises: Promise<boolean>[] = []\n const { head } = childWindow.document\n\n const isCurrent = () => controller.version === version\n const { parentStylesheets } = snapshot\n\n const desiredStylesheetKeys = new Set<string>()\n for (const link of parentStylesheets) {\n if (link.href) desiredStylesheetKeys.add(link.href)\n }\n\n const existingSyncedLinks = Array.from(\n head.querySelectorAll(\n `link[rel=\"stylesheet\"][${WEBSPATIAL_SYNC_ATTR}=\"1\"]`,\n ),\n ) as HTMLLinkElement[]\n for (const link of existingSyncedLinks) {\n const key = link.getAttribute(WEBSPATIAL_SYNC_KEY_ATTR) ?? link.href\n if (!desiredStylesheetKeys.has(key)) link.parentNode?.removeChild(link)\n }\n\n syncInlineStylesToChild(head, snapshot)\n\n const currentKeys = new Set<string>()\n const currentSyncedLinks = Array.from(\n head.querySelectorAll(\n `link[rel=\"stylesheet\"][${WEBSPATIAL_SYNC_ATTR}=\"1\"]`,\n ),\n ) as HTMLLinkElement[]\n for (const link of currentSyncedLinks) {\n currentKeys.add(link.getAttribute(WEBSPATIAL_SYNC_KEY_ATTR) ?? link.href)\n }\n\n for (const link of parentStylesheets) {\n const key = link.href\n if (!key || currentKeys.has(key)) continue\n const node = link.cloneNode(true) as HTMLLinkElement\n node.setAttribute(WEBSPATIAL_SYNC_ATTR, '1')\n node.setAttribute(WEBSPATIAL_SYNC_KEY_ATTR, key)\n styleLoadedPromises.push(\n asyncLoadStyleToChildWindow(childWindow, node, isCurrent),\n )\n }\n\n // sync className\n childWindow.document.documentElement.className =\n snapshot.documentElementClassName\n\n return Promise.all(styleLoadedPromises)\n}\n\ntype SyncScheduleTiming = 'immediate' | 'delayed' | 'afterHostLayout'\n\ntype HeadSyncScheduler = {\n disposed: boolean\n}\n\nconst headSyncSchedulers = new WeakMap<WindowProxy, HeadSyncScheduler>()\n\nfunction getHeadSyncScheduler(childWindow: WindowProxy): HeadSyncScheduler {\n const prev = headSyncSchedulers.get(childWindow)\n if (prev) return prev\n const next: HeadSyncScheduler = {\n disposed: false,\n }\n headSyncSchedulers.set(childWindow, next)\n return next\n}\n\ntype SyncTimingFromMutation = 'immediate' | 'delayed'\n\ntype PendingWave = {\n timing: SyncScheduleTiming\n broadcast: boolean\n targets: Set<WindowProxy>\n onComplete: Map<WindowProxy, () => void>\n}\n\nconst activeTargets = new Set<WindowProxy>()\n\nlet headObserver: MutationObserver | null = null\nlet domUpdatedHandler: (() => void) | null = null\nlet originalInsertRule: CSSStyleSheet['insertRule'] | undefined\nlet originalDeleteRule: CSSStyleSheet['deleteRule'] | undefined\nlet pendingWave: PendingWave | null = null\nlet flushQueued: SyncScheduleTiming | null = null\nlet delayTimer: number | undefined\nlet afterHostLayoutRaf: number | undefined\n\nconst timingPriority: Record<SyncScheduleTiming, number> = {\n delayed: 1,\n afterHostLayout: 2,\n immediate: 3,\n}\n\nfunction isParentHeadStyleSheet(sheet: CSSStyleSheet) {\n const ownerNode = (sheet as CSSStyleSheet & { ownerNode?: Node }).ownerNode\n if (\n ownerNode instanceof HTMLStyleElement &&\n ownerNode.ownerDocument === document &&\n document.head.contains(ownerNode)\n ) {\n return true\n }\n\n return Array.from(document.head.querySelectorAll('style')).some(\n style => style.sheet === sheet,\n )\n}\n\nfunction getSyncTiming(\n mutations?: MutationRecord[] | null,\n): SyncTimingFromMutation | null {\n if (!Array.isArray(mutations) || mutations.length === 0) return null\n let hasDelayed = false\n for (const mutation of mutations) {\n if (mutation.type === 'characterData') {\n const parent = mutation.target.parentElement\n if (parent?.tagName === 'STYLE') return 'immediate'\n }\n\n const nodes: Node[] = [\n mutation.target,\n ...Array.from(mutation.addedNodes),\n ...Array.from(mutation.removedNodes),\n ]\n for (const node of nodes) {\n if (!(node instanceof Element)) continue\n const tag = node.tagName\n if (tag === 'STYLE') return 'immediate'\n if (tag === 'LINK') {\n const { rel } = node as HTMLLinkElement\n if (rel && rel.toLowerCase() === 'stylesheet') hasDelayed = true\n }\n }\n }\n return hasDelayed ? 'delayed' : null\n}\n\nfunction installCssomRuleObserver() {\n if (typeof CSSStyleSheet === 'undefined' || originalInsertRule) return\n\n originalInsertRule = CSSStyleSheet.prototype.insertRule\n originalDeleteRule = CSSStyleSheet.prototype.deleteRule\n\n CSSStyleSheet.prototype.insertRule = function patchedInsertRule(\n rule: string,\n index?: number,\n ) {\n const result = originalInsertRule!.call(this, rule, index)\n if (isParentHeadStyleSheet(this)) {\n enqueueParentHeadSync('immediate', { broadcast: true })\n }\n return result\n }\n\n CSSStyleSheet.prototype.deleteRule = function patchedDeleteRule(\n index: number,\n ) {\n originalDeleteRule!.call(this, index)\n if (isParentHeadStyleSheet(this)) {\n enqueueParentHeadSync('immediate', { broadcast: true })\n }\n }\n}\n\nfunction uninstallCssomRuleObserver() {\n if (originalInsertRule) {\n CSSStyleSheet.prototype.insertRule = originalInsertRule\n }\n if (originalDeleteRule) {\n CSSStyleSheet.prototype.deleteRule = originalDeleteRule\n }\n originalInsertRule = undefined\n originalDeleteRule = undefined\n}\n\nfunction installParentHeadSyncRegistry() {\n if (!headObserver) {\n headObserver = new MutationObserver(mutations => {\n const timing = getSyncTiming(mutations)\n if (!timing) return\n enqueueParentHeadSync(timing, { broadcast: true })\n })\n headObserver.observe(document.head, {\n childList: true,\n characterData: true,\n subtree: true,\n })\n }\n\n if (!domUpdatedHandler) {\n domUpdatedHandler = () =>\n enqueueParentHeadSync('afterHostLayout', { broadcast: true })\n document.addEventListener(\n SpatialStyleInfoUpdateEvent.domUpdated,\n domUpdatedHandler,\n )\n }\n\n installCssomRuleObserver()\n}\n\nfunction clearQueuedFlush() {\n if (delayTimer) {\n window.clearTimeout(delayTimer)\n delayTimer = undefined\n }\n if (afterHostLayoutRaf) {\n window.cancelAnimationFrame(afterHostLayoutRaf)\n afterHostLayoutRaf = undefined\n }\n flushQueued = null\n}\n\nfunction teardownParentHeadSyncRegistry() {\n headObserver?.disconnect()\n headObserver = null\n\n if (domUpdatedHandler) {\n document.removeEventListener(\n SpatialStyleInfoUpdateEvent.domUpdated,\n domUpdatedHandler,\n )\n domUpdatedHandler = null\n }\n\n uninstallCssomRuleObserver()\n clearQueuedFlush()\n pendingWave = null\n}\n\nfunction teardownParentHeadSyncRegistryIfEmpty() {\n if (activeTargets.size > 0) return\n teardownParentHeadSyncRegistry()\n}\n\nfunction isWindowDisposed(childWindow: WindowProxy) {\n return headSyncSchedulers.get(childWindow)?.disposed === true\n}\n\nfunction getOrCreatePendingWave(timing: SyncScheduleTiming) {\n if (!pendingWave) {\n pendingWave = {\n timing,\n broadcast: false,\n targets: new Set(),\n onComplete: new Map(),\n }\n return pendingWave\n }\n\n if (timingPriority[timing] > timingPriority[pendingWave.timing]) {\n pendingWave.timing = timing\n }\n return pendingWave\n}\n\nasync function flushHeadSyncWave() {\n const wave = pendingWave\n pendingWave = null\n flushQueued = null\n delayTimer = undefined\n afterHostLayoutRaf = undefined\n if (!wave) return\n\n const targets = (\n wave.broadcast ? Array.from(activeTargets) : Array.from(wave.targets)\n ).filter(childWindow => !isWindowDisposed(childWindow))\n\n if (targets.length === 0) return\n\n const snapshot = captureParentHeadSnapshot()\n await Promise.all(\n targets.map(async childWindow => {\n await syncParentHeadToChild(childWindow, snapshot)\n wave.onComplete.get(childWindow)?.()\n }),\n )\n}\n\nfunction queuePendingWaveFlush(timing: SyncScheduleTiming) {\n if (timing === 'delayed') {\n if (flushQueued) return\n flushQueued = 'delayed'\n delayTimer = window.setTimeout(() => {\n void flushHeadSyncWave()\n }, 100)\n return\n }\n\n if (delayTimer) {\n window.clearTimeout(delayTimer)\n delayTimer = undefined\n }\n\n if (timing === 'immediate') {\n if (afterHostLayoutRaf) {\n window.cancelAnimationFrame(afterHostLayoutRaf)\n afterHostLayoutRaf = undefined\n }\n if (flushQueued === 'immediate') return\n flushQueued = 'immediate'\n queueMicrotask(() => {\n if (flushQueued !== 'immediate') return\n void flushHeadSyncWave()\n })\n return\n }\n\n if (flushQueued === 'immediate' || flushQueued === 'afterHostLayout') return\n\n flushQueued = 'afterHostLayout'\n queueMicrotask(() => {\n if (flushQueued !== 'afterHostLayout') return\n afterHostLayoutRaf = window.requestAnimationFrame(() => {\n if (flushQueued !== 'afterHostLayout') return\n void flushHeadSyncWave()\n })\n })\n}\n\nfunction enqueueParentHeadSync(\n timing: SyncScheduleTiming,\n options:\n | { broadcast: true; onComplete?: never }\n | {\n broadcast?: false\n childWindow: WindowProxy\n onComplete?: () => void\n },\n) {\n const wave = getOrCreatePendingWave(timing)\n if (options.broadcast) {\n wave.broadcast = true\n } else {\n const scheduler = getHeadSyncScheduler(options.childWindow)\n if (scheduler.disposed) return\n wave.targets.add(options.childWindow)\n if (options.onComplete) {\n wave.onComplete.set(options.childWindow, options.onComplete)\n }\n }\n queuePendingWaveFlush(wave.timing)\n}\n\nfunction addParentHeadSyncTarget(childWindow: WindowProxy) {\n const scheduler = getHeadSyncScheduler(childWindow)\n scheduler.disposed = false\n activeTargets.add(childWindow)\n installParentHeadSyncRegistry()\n\n let unregistered = false\n return () => {\n if (unregistered) return\n unregistered = true\n activeTargets.delete(childWindow)\n teardownParentHeadSyncRegistryIfEmpty()\n }\n}\n\nexport function registerParentHeadSyncTarget(childWindow: WindowProxy) {\n const unregister = addParentHeadSyncTarget(childWindow)\n scheduleSyncParentHeadToChild(childWindow)\n return unregister\n}\n\n/**\n * Coalesced head sync for a portal window. `afterHostLayout` runs after the next\n * animation frame so CSS-in-JS (e.g. styled-components) can commit head rules\n * that follow a spatial host class/style update.\n */\nexport function scheduleSyncParentHeadToChild(\n childWindow: WindowProxy,\n timing: SyncScheduleTiming = 'immediate',\n onComplete?: () => void,\n) {\n enqueueParentHeadSync(timing, {\n broadcast: false,\n childWindow,\n onComplete: timing === 'afterHostLayout' ? onComplete : undefined,\n })\n}\n\nexport function disposeSyncParentHeadToChild(childWindow: WindowProxy) {\n const scheduler = headSyncSchedulers.get(childWindow)\n if (scheduler) scheduler.disposed = true\n activeTargets.delete(childWindow)\n teardownParentHeadSyncRegistryIfEmpty()\n headSyncSchedulers.delete(childWindow)\n}\n\nexport const __parentHeadSyncRegistryTest__ = {\n getActiveTargetCount: () => activeTargets.size,\n getObserverInstalled: () => headObserver != null,\n flushPendingWaveForTest: flushHeadSyncWave,\n registerTarget(childWindow: WindowProxy, options?: { immediate?: boolean }) {\n const unregister = addParentHeadSyncTarget(childWindow)\n if (options?.immediate ?? true) {\n scheduleSyncParentHeadToChild(childWindow)\n }\n return unregister\n },\n reset: () => {\n activeTargets.clear()\n teardownParentHeadSyncRegistry()\n },\n}\n","import { useEffect, useRef, useState } from 'react'\nimport { PortalInstanceObject } from '../context/PortalInstanceContext'\nimport { SpatializedElement } from '@webspatial/core-sdk'\n\nexport function useSpatializedElement(\n createSpatializedElement: () => Promise<SpatializedElement | null>,\n portalInstanceObject: PortalInstanceObject,\n) {\n const [spatializedElement, setSpatializedElement] =\n useState<SpatializedElement>()\n // State drives re-renders and the returned value; it can't be in the effect\n // deps or we get an infinite loop (set → effect re-runs → create → set).\n // The element is created inside .then(), so cleanup may run before or after\n // the promise resolves. The ref is the shared store so cleanup can always\n // find and destroy the current element.\n const elementRef = useRef<SpatializedElement | undefined>(undefined)\n\n useEffect(() => {\n let cancelled = false\n\n createSpatializedElement().then(\n (inSpatializedElement: SpatializedElement | null) => {\n if (!inSpatializedElement) return\n if (cancelled) {\n inSpatializedElement.destroy()\n return\n }\n\n const previous = elementRef.current\n if (previous && previous !== inSpatializedElement) {\n previous.destroy()\n }\n\n elementRef.current = inSpatializedElement\n portalInstanceObject.attachSpatializedElement(inSpatializedElement)\n setSpatializedElement(inSpatializedElement)\n },\n )\n\n // HMR / effect re-run: cancel in-flight work only; keep the live element\n // visible until a replacement is attached (see second effect for teardown).\n return () => {\n cancelled = true\n }\n }, [createSpatializedElement, portalInstanceObject])\n\n useEffect(() => {\n return () => {\n const el = elementRef.current\n if (el) {\n el.destroy()\n elementRef.current = undefined\n setSpatializedElement(undefined)\n }\n }\n }, [portalInstanceObject])\n\n return spatializedElement\n}\n","import type { SpatializedElement } from '@webspatial/core-sdk'\nimport { useEffect } from 'react'\nimport type { SpatializedMotionBinding } from './motionBindingTypes'\n\n/**\n * Options for binding a resolved runtime element to a spatialized motion\n * binding.\n */\ninterface UseBindSpatializedMotionOptions {\n /** The opaque motion binding returned by `useAnimation()`. */\n binding?: SpatializedMotionBinding\n\n /** The resolved runtime element that should be attached to the binding. */\n element?: SpatializedElement | null\n}\n\n/**\n * Checks whether the resolved spatialized element can host motion.\n *\n * @param element - The resolved runtime element candidate.\n * @returns Whether the element is a supported motion target.\n */\nfunction isSupportedSpatializedMotionElement(\n element: SpatializedElement,\n): boolean {\n switch (element.kind) {\n case 'spatialized2d':\n case 'static3d':\n case 'dynamic3d':\n return true\n default:\n return false\n }\n}\n\n/**\n * Attaches a resolved runtime element to a spatialized motion binding.\n *\n * @param options - Binding lifecycle options.\n */\nexport function useBindSpatializedMotion({\n binding,\n element,\n}: UseBindSpatializedMotionOptions): void {\n useEffect(() => {\n if (!binding || !element) return\n if (!isSupportedSpatializedMotionElement(element)) return\n\n binding.__setElement?.(element)\n\n return () => {\n binding.__onUnbind?.(element)\n }\n }, [binding, element])\n}\n","import { ForwardedRef, useCallback, useEffect, useRef } from 'react'\nimport { SpatialCustomStyleVars, SpatializedElementRef } from '../types'\nimport { supports } from '@webspatial/core-sdk'\nimport { extractAndRemoveCustomProperties, joinToCSSText } from '../utils'\nimport { ensureSpatialDefaultStyleInRoot } from '../StandardSpatializedContainer'\n\n/**\n * Owns the spatialized behavior installed on the standard host element and\n * keeps the host ↔ probe pair (`StandardSpatializedContainer` ↔\n * `TransformVisibilityTaskContainer`) in sync.\n *\n * The host is exposed to consumers as `ref.current` — a real `HTMLElement` —\n * with property descriptors layered on via `Object.defineProperty` (style,\n * className, removeAttribute, xrClientDepth, xrOffsetBack, extraRefProps).\n * `style.transform` / `style.visibility` writes are forwarded to the probe\n * so they reach the platform via `useSpatialTransformVisibility`.\n *\n * Several non-trivial invariants must hold for the hidden-host CSS rules to\n * keep working — `xr-spatial-default` always present as a class token,\n * `data-xr-host` always present, transform/visibility never written inline\n * on the host. See `../ARCHITECTURE.md` (Invariants) for the full list and\n * the reasoning behind each.\n */\nexport class SpatialContainerRefProxy<T extends SpatializedElementRef> {\n private transformVisibilityTaskContainerDom: HTMLElement | null = null\n /** Raw Standard host element (styled root). Used to mirror class onto the transform probe. */\n private standardRawDom: HTMLElement | null = null\n private standardClassObserver: MutationObserver | null = null\n /**\n * When set, Standard's DOM className is forwarded here so TransformVisibilityTaskContainer\n * can render it from React state (avoids React clobbering imperative class updates).\n */\n private mirrorClassNotify: ((className: string) => void) | null = null\n /** Last class string applied to the probe + used to skip redundant syncs. */\n private lastMirroredClassName: string | null = null\n /** Coalesce multiple class sync triggers in the same turn (Observer + classList, etc.). */\n private classSyncMicrotaskQueued = false\n private ref: ForwardedRef<SpatializedElementRef<T>>\n public domProxy?: T | null\n /** Last value dispatched to `ref` (undefined = none yet); avoids duplicate null/proxy writes. */\n private lastOutgoingToRef: T | null | undefined = undefined\n private installedProperties: PropertyKey[] = []\n\n // extre ref props, used to add extra props to ref\n private extraRefProps?: ((domProxy: T) => Record<string, unknown>) | undefined\n\n constructor(\n ref: ForwardedRef<SpatializedElementRef<T>>,\n extraRefProps?: (domProxy: T) => Record<string, unknown>,\n ) {\n this.ref = ref\n this.extraRefProps = extraRefProps\n }\n\n setMirrorClassNotify(fn: ((className: string) => void) | null) {\n this.mirrorClassNotify = fn\n if (fn && this.standardRawDom) {\n this.flushSyncTransformClassFromStandard(true)\n }\n }\n\n private disconnectStandardClassObserver() {\n this.standardClassObserver?.disconnect()\n this.standardClassObserver = null\n }\n\n private attachStandardClassObserver() {\n this.disconnectStandardClassObserver()\n if (!this.standardRawDom) {\n return\n }\n this.standardClassObserver = new MutationObserver(() => {\n // The hidden-placeholder CSS rule is scoped to\n // `.xr-spatial-default[data-xr-host]`, so any native path that strips\n // the class (`setAttribute('class', …)`, `classList.remove(...)`,\n // `classList.replace(...)`, third-party DOM helpers) would un-hide the\n // 2D host. The className descriptor only intercepts `el.className =`\n // assignment; restore the class here so all attribute-mutation paths\n // converge on the same invariant.\n this.ensureSpatialDefaultClass()\n this.scheduleSyncTransformClassFromStandard()\n })\n this.standardClassObserver.observe(this.standardRawDom, {\n attributes: true,\n attributeFilter: ['class'],\n })\n }\n\n private ensureSpatialDefaultClass() {\n const dom = this.standardRawDom\n if (!dom) return\n // Token-based check via classList rather than `indexOf('xr-spatial-default')`,\n // so a class like `foo-xr-spatial-default-theme` does not satisfy the\n // invariant — the CSS rule is keyed on the real `.xr-spatial-default`\n // class token, not a substring.\n if (dom.classList.contains('xr-spatial-default')) return\n dom.classList.add('xr-spatial-default')\n }\n\n /**\n * Merge multiple sync requests (e.g. classList hook + MutationObserver) into one microtask.\n */\n private scheduleSyncTransformClassFromStandard() {\n if (this.classSyncMicrotaskQueued) {\n return\n }\n this.classSyncMicrotaskQueued = true\n queueMicrotask(() => {\n this.classSyncMicrotaskQueued = false\n this.flushSyncTransformClassFromStandard(false)\n })\n }\n\n /**\n * Source of truth: Standard host DOM (incl. styled-components runtime class changes).\n * @param force when true, skip same-string short-circuit (e.g. mirror notify just registered).\n */\n private flushSyncTransformClassFromStandard(force: boolean) {\n if (!this.standardRawDom) {\n return\n }\n const name = this.standardRawDom.className\n const probe = this.transformVisibilityTaskContainerDom\n if (\n !force &&\n probe &&\n probe.className === name &&\n this.lastMirroredClassName === name\n ) {\n return\n }\n this.lastMirroredClassName = name\n if (probe) {\n probe.className = name\n }\n this.mirrorClassNotify?.(name)\n }\n\n updateStandardSpatializedContainerDom(dom: HTMLElement | null) {\n if (!dom) {\n this.disconnectStandardClassObserver()\n this.clearInstalledProperties()\n this.standardRawDom = null\n this.lastMirroredClassName = null\n this.domProxy = undefined\n this.updateDomProxyToRef()\n return\n }\n\n if (this.standardRawDom === dom && this.domProxy) {\n this.scheduleSyncTransformClassFromStandard()\n return\n }\n\n this.clearInstalledProperties()\n this.standardRawDom = dom\n this.domProxy = dom as SpatializedElementRef<T>\n this.installSpatialRefBehavior(dom as SpatializedElementRef<T>)\n\n // Make sure the spatial default stylesheet is reachable from this host.\n // initPolyfill() injects it into `document`, but document-level rules do\n // not cross shadow boundaries — so a host mounted inside a ShadowRoot\n // would otherwise miss the `.xr-spatial-default[data-xr-host]` hiding\n // rule (and the spatial CSS variable defaults). The helper is idempotent\n // per root.\n const root = dom.getRootNode()\n if (root === document || root instanceof ShadowRoot) {\n ensureSpatialDefaultStyleInRoot(root as Document | ShadowRoot)\n }\n\n // Attach the class observer BEFORE publishing the ref. If a user-supplied\n // callback ref synchronously mutates the class via a native API that\n // bypasses the className descriptor (`node.setAttribute('class', …)`,\n // `node.classList.remove('xr-spatial-default')`, …), the resulting\n // MutationRecord must reach the self-heal in `attachStandardClassObserver`\n // — otherwise xr-spatial-default would be lost without restoration and\n // the host would un-hide. Do not reorder these two calls without a\n // regression test.\n this.attachStandardClassObserver()\n this.updateDomProxyToRef()\n this.scheduleSyncTransformClassFromStandard()\n }\n\n private clearInstalledProperties() {\n const dom = this.standardRawDom\n if (!dom) return\n for (const prop of this.installedProperties) {\n delete (dom as any)[prop]\n }\n this.installedProperties = []\n }\n\n private defineDomProperty(\n dom: HTMLElement,\n prop: PropertyKey,\n descriptor: PropertyDescriptor,\n ) {\n Object.defineProperty(dom, prop, {\n configurable: true,\n ...descriptor,\n })\n this.installedProperties.push(prop)\n }\n\n private installSpatialRefBehavior(dom: SpatializedElementRef<T>) {\n const self = this\n\n const rawStyle = dom.style\n const rawRemoveProperty = rawStyle.removeProperty.bind(rawStyle)\n const rawGetPropertyValue = rawStyle.getPropertyValue.bind(rawStyle)\n const rawRemoveAttribute = dom.removeAttribute.bind(dom)\n const spatialStyleProperties = ['visibility', 'transform']\n const styleProxy = new Proxy<CSSStyleDeclaration>(rawStyle, {\n get(target, prop) {\n if (prop === 'visibility' || prop === 'transform') {\n return self.transformVisibilityTaskContainerDom?.style.getPropertyValue(\n prop as string,\n )\n }\n const value = Reflect.get(target, prop)\n if (typeof value === 'function') {\n if (\n prop === 'setProperty' ||\n prop === 'removeProperty' ||\n prop === 'getPropertyValue'\n ) {\n return function (this: any, ...args: any[]) {\n const [property] = args\n\n if (spatialStyleProperties.includes(property)) {\n if (prop === 'setProperty') {\n const [, kValue, priority] = args\n self.transformVisibilityTaskContainerDom?.style.setProperty(\n property,\n kValue as string,\n priority as string | undefined,\n )\n } else if (prop === 'removeProperty') {\n return self.transformVisibilityTaskContainerDom?.style.removeProperty(\n property,\n )\n } else if (prop === 'getPropertyValue') {\n return self.transformVisibilityTaskContainerDom?.style.getPropertyValue(\n property,\n )\n }\n return undefined\n }\n return value.apply(this, args)\n }.bind(target)\n }\n return value.bind(target)\n }\n return value\n },\n set(target, prop, value) {\n if (prop === 'visibility') {\n self.transformVisibilityTaskContainerDom?.style.setProperty(\n 'visibility',\n value,\n )\n return true\n }\n if (prop === 'transform') {\n self.transformVisibilityTaskContainerDom?.style.setProperty(\n 'transform',\n value,\n )\n return true\n }\n\n if (Object.values(SpatialCustomStyleVars).includes(prop as string)) {\n target.setProperty(prop as string, value as string)\n return true\n }\n if (prop === 'cssText') {\n // parse cssText, filter out spatialStyle like transform/visibility\n const { extractedValues, filteredCssText } =\n extractAndRemoveCustomProperties(\n value as string,\n spatialStyleProperties,\n )\n\n // update cssText for transformVisibilityTaskContainerDom\n spatialStyleProperties.forEach(key => {\n if (extractedValues[key]) {\n self.transformVisibilityTaskContainerDom?.style.setProperty(\n key,\n extractedValues[key],\n )\n } else {\n rawRemoveProperty(key)\n }\n })\n\n const appendedCSSText = joinToCSSText({\n transform: 'none',\n visibility: 'hidden',\n })\n\n return Reflect.set(\n target,\n prop,\n [appendedCSSText, filteredCssText].join(';'),\n )\n }\n return Reflect.set(target, prop, value)\n },\n })\n\n this.defineDomProperty(dom, 'style', {\n get() {\n return styleProxy\n },\n set(value) {\n styleProxy.cssText = String(value)\n },\n })\n\n this.defineDomProperty(dom, 'className', {\n get() {\n return dom.getAttribute('class') ?? ''\n },\n set(value) {\n // Always preserve the real `xr-spatial-default` class token. Without\n // it the host loses both the spatial CSS vars and the\n // `.xr-spatial-default[data-xr-host]` hidden-placeholder rule, which\n // would un-hide the 2D host. Apply the value first, then re-append\n // via classList (which uses spec-correct token semantics) so values\n // like `foo-xr-spatial-default-theme` — substring-matching but not a\n // real token — still trigger restoration.\n dom.setAttribute('class', String(value))\n if (!dom.classList.contains('xr-spatial-default')) {\n dom.classList.add('xr-spatial-default')\n }\n self.scheduleSyncTransformClassFromStandard()\n },\n })\n\n this.defineDomProperty(dom, 'removeAttribute', {\n value(property: string) {\n if (property === 'style') {\n rawStyle.cssText =\n 'visibility: hidden; transition: none; transform: none;'\n self.transformVisibilityTaskContainerDom?.style.removeProperty(\n 'visibility',\n )\n self.transformVisibilityTaskContainerDom?.style.removeProperty(\n 'transform',\n )\n return\n }\n if (property === 'class') {\n dom.className = 'xr-spatial-default'\n return\n }\n return rawRemoveAttribute(property)\n },\n })\n\n if (supports('xrClientDepth')) {\n this.defineDomProperty(dom, 'xrClientDepth', {\n get() {\n return rawGetPropertyValue(SpatialCustomStyleVars.depth)\n },\n })\n }\n if (supports('xrOffsetBack')) {\n this.defineDomProperty(dom, 'xrOffsetBack', {\n get() {\n return rawGetPropertyValue(SpatialCustomStyleVars.back)\n },\n })\n }\n\n if (this.extraRefProps) {\n const extraProps = this.extraRefProps(dom)\n for (const prop of Object.keys(extraProps)) {\n this.defineDomProperty(dom, prop, {\n get() {\n return extraProps[prop]\n },\n set(value) {\n extraProps[prop] = value\n },\n })\n }\n }\n }\n\n updateTransformVisibilityTaskContainerDom(dom: HTMLElement | null) {\n this.transformVisibilityTaskContainerDom = dom\n if (!dom) {\n this.lastMirroredClassName = null\n }\n this.scheduleSyncTransformClassFromStandard()\n this.updateDomProxyToRef()\n }\n\n private updateDomProxyToRef() {\n const ref = this.ref\n if (!ref) {\n return\n }\n const next: T | null =\n this.domProxy && this.transformVisibilityTaskContainerDom\n ? this.domProxy\n : null\n if (this.lastOutgoingToRef === next) {\n return\n }\n this.lastOutgoingToRef = next\n if (next) {\n if (typeof ref === 'function') {\n ref(next)\n } else {\n ref.current = next\n }\n } else {\n if (typeof ref === 'function') {\n ref(null)\n } else {\n ref.current = null\n }\n }\n }\n\n updateRef(ref: ForwardedRef<SpatializedElementRef<T>>) {\n if (this.ref === ref) {\n return\n }\n this.ref = ref\n this.lastOutgoingToRef = undefined\n this.updateDomProxyToRef()\n }\n}\n\nexport function useDomProxy<T extends SpatializedElementRef>(\n ref: ForwardedRef<T>,\n extraRefProps?: (domProxy: T) => Record<string, unknown>,\n) {\n const spatialContainerRefProxy = useRef<SpatialContainerRefProxy<T>>(\n new SpatialContainerRefProxy<T>(ref, extraRefProps),\n )\n\n useEffect(() => {\n spatialContainerRefProxy.current.updateRef(ref)\n }, [ref])\n\n const transformVisibilityTaskContainerCallback = useCallback(\n (el: HTMLElement | null) => {\n spatialContainerRefProxy.current.updateTransformVisibilityTaskContainerDom(\n el,\n )\n },\n [],\n )\n\n const standardSpatializedContainerCallback = useCallback(\n (el: HTMLElement | null) => {\n spatialContainerRefProxy.current.updateStandardSpatializedContainerDom(el)\n },\n [],\n )\n\n return {\n transformVisibilityTaskContainerCallback,\n standardSpatializedContainerCallback,\n spatialContainerRefProxy,\n }\n}\n","import { createContext, useContext } from 'react'\n\nexport const InsideAttachmentContext = createContext(false)\nexport const useInsideAttachment = () => useContext(InsideAttachmentContext)\n","import { RefObject } from 'react'\nimport { SpatialContainerRefProxy } from './useDomProxy'\nimport {\n SpatializedElementRef,\n SpatialTapEvent,\n SpatialDragStartEvent,\n SpatialDragEndEvent,\n SpatialDragEvent,\n SpatialRotateEvent,\n SpatialRotateEndEvent,\n SpatialMagnifyEndEvent,\n SpatialMagnifyEvent,\n} from '../types'\nimport { SpatializedContainerObject } from '../context/SpatializedContainerContext'\n\nexport interface SpatialEvents<\n T extends SpatializedElementRef = SpatializedElementRef,\n> {\n onSpatialTap?: (event: SpatialTapEvent<T>) => void\n onSpatialDragStart?: (event: SpatialDragStartEvent<T>) => void\n onSpatialDrag?: (event: SpatialDragEvent<T>) => void\n onSpatialDragEnd?: (event: SpatialDragEndEvent<T>) => void\n onSpatialRotate?: (event: SpatialRotateEvent<T>) => void\n onSpatialRotateEnd?: (event: SpatialRotateEndEvent<T>) => void\n onSpatialMagnify?: (event: SpatialMagnifyEvent<T>) => void\n onSpatialMagnifyEnd?: (event: SpatialMagnifyEndEvent<T>) => void\n}\n\nfunction createEventProxy<\n T extends SpatializedElementRef,\n E extends { currentTarget: T },\n>(\n event: E,\n currentTargetGetter: () => T,\n offsetXGetter?: (event: E) => number | undefined,\n offsetYGetter?: (event: E) => number | undefined,\n offsetZGetter?: (event: E) => number | undefined,\n clientXGetter?: (event: E) => number | undefined,\n clientYGetter?: (event: E) => number | undefined,\n clientZGetter?: (event: E) => number | undefined,\n translationXGetter?: (event: E) => number | undefined,\n translationYGetter?: (event: E) => number | undefined,\n translationZGetter?: (event: E) => number | undefined,\n quaternionGetter?: (\n event: E,\n ) => import('@webspatial/core-sdk').Quaternion | undefined,\n magnificationGetter?: (event: E) => number | undefined,\n): E {\n return new Proxy(event, {\n get(target, prop) {\n if (prop === 'currentTarget') {\n return currentTargetGetter()\n }\n if (prop === 'isTrusted') {\n return true\n }\n if (prop === 'bubbles') {\n return false\n }\n if (prop === 'offsetX' && offsetXGetter) {\n return offsetXGetter(target) ?? 0\n }\n if (prop === 'offsetY' && offsetYGetter) {\n return offsetYGetter(target) ?? 0\n }\n if (prop === 'offsetZ' && offsetZGetter) {\n return offsetZGetter(target) ?? 0\n }\n if (prop === 'clientX' && clientXGetter) {\n return clientXGetter(target) ?? 0\n }\n if (prop === 'clientY' && clientYGetter) {\n return clientYGetter(target) ?? 0\n }\n if (prop === 'clientZ' && clientZGetter) {\n return clientZGetter(target) ?? 0\n }\n if (prop === 'translationX' && translationXGetter) {\n return translationXGetter(target) ?? 0\n }\n if (prop === 'translationY' && translationYGetter) {\n return translationYGetter(target) ?? 0\n }\n if (prop === 'translationZ' && translationZGetter) {\n return translationZGetter(target) ?? 0\n }\n if (prop === 'quaternion' && quaternionGetter) {\n return quaternionGetter(target) ?? { x: 0, y: 0, z: 0, w: 1 }\n }\n if (prop === 'magnification' && magnificationGetter) {\n return magnificationGetter(target) ?? 1\n }\n return Reflect.get(target, prop)\n },\n })\n}\n\nfunction createEventHandler<\n T extends SpatializedElementRef,\n E extends { currentTarget: T },\n>(\n handler: ((event: E) => void) | undefined,\n currentTargetGetter: () => T,\n offsetXGetter?: (event: E) => number | undefined,\n offsetYGetter?: (event: E) => number | undefined,\n offsetZGetter?: (event: E) => number | undefined,\n clientXGetter?: (event: E) => number | undefined,\n clientYGetter?: (event: E) => number | undefined,\n clientZGetter?: (event: E) => number | undefined,\n translationXGetter?: (event: E) => number | undefined,\n translationYGetter?: (event: E) => number | undefined,\n translationZGetter?: (event: E) => number | undefined,\n quaternionGetter?: (\n event: E,\n ) => import('@webspatial/core-sdk').Quaternion | undefined,\n magnificationGetter?: (event: E) => number | undefined,\n): ((event: E) => void) | undefined {\n return handler\n ? (event: E) => {\n const proxyEvent = createEventProxy<T, E>(\n event,\n currentTargetGetter,\n offsetXGetter,\n offsetYGetter,\n offsetZGetter,\n clientXGetter,\n clientYGetter,\n clientZGetter,\n translationXGetter,\n translationYGetter,\n translationZGetter,\n quaternionGetter,\n magnificationGetter,\n )\n handler(proxyEvent)\n }\n : undefined\n}\n\nexport function useSpatialEventsBase<T extends SpatializedElementRef>(\n spatialEvents: SpatialEvents<T>,\n currentTargetGetter: () => T,\n) {\n const onSpatialTap = createEventHandler<T, SpatialTapEvent<T>>(\n spatialEvents.onSpatialTap,\n currentTargetGetter,\n // offsetX/Y/Z come from local coordinates\n (ev: SpatialTapEvent<T>) => ev.detail?.location3D?.x,\n (ev: SpatialTapEvent<T>) => ev.detail?.location3D?.y,\n (ev: SpatialTapEvent<T>) => ev.detail?.location3D?.z,\n // clientX/Y/Z come from global scene coordinates\n (ev: SpatialTapEvent<T>) => ev.detail?.globalLocation3D?.x,\n (ev: SpatialTapEvent<T>) => ev.detail?.globalLocation3D?.y,\n (ev: SpatialTapEvent<T>) => ev.detail?.globalLocation3D?.z,\n )\n const onSpatialDrag = createEventHandler<T, SpatialDragEvent<T>>(\n spatialEvents.onSpatialDrag,\n currentTargetGetter,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n (ev: SpatialDragEvent<T>) => ev.detail?.translation3D?.x,\n (ev: SpatialDragEvent<T>) => ev.detail?.translation3D?.y,\n (ev: SpatialDragEvent<T>) => ev.detail?.translation3D?.z,\n )\n\n const onSpatialDragEnd = createEventHandler<T, SpatialDragEndEvent<T>>(\n spatialEvents.onSpatialDragEnd,\n currentTargetGetter,\n )\n\n const onSpatialRotate = createEventHandler<T, SpatialRotateEvent<T>>(\n spatialEvents.onSpatialRotate,\n currentTargetGetter,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n (ev: SpatialRotateEvent<T>) => ev.detail?.quaternion,\n )\n\n const onSpatialRotateEnd = createEventHandler<T, SpatialRotateEndEvent<T>>(\n spatialEvents.onSpatialRotateEnd,\n currentTargetGetter,\n )\n\n const onSpatialMagnify = createEventHandler<T, SpatialMagnifyEvent<T>>(\n spatialEvents.onSpatialMagnify,\n currentTargetGetter,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n (ev: SpatialMagnifyEvent<T>) => ev.detail?.magnification,\n )\n\n const onSpatialMagnifyEnd = createEventHandler<T, SpatialMagnifyEndEvent<T>>(\n spatialEvents.onSpatialMagnifyEnd,\n currentTargetGetter,\n )\n\n const onSpatialDragStart = createEventHandler<T, SpatialDragStartEvent<T>>(\n spatialEvents.onSpatialDragStart,\n currentTargetGetter,\n (ev: SpatialDragStartEvent<T>) => ev.detail?.startLocation3D?.x,\n (ev: SpatialDragStartEvent<T>) => ev.detail?.startLocation3D?.y,\n (ev: SpatialDragStartEvent<T>) => ev.detail?.startLocation3D?.z,\n (ev: SpatialDragStartEvent<T>) => ev.detail?.globalLocation3D?.x,\n (ev: SpatialDragStartEvent<T>) => ev.detail?.globalLocation3D?.y,\n (ev: SpatialDragStartEvent<T>) => ev.detail?.globalLocation3D?.z,\n )\n\n return {\n onSpatialTap,\n onSpatialDragStart,\n onSpatialDrag,\n onSpatialDragEnd,\n onSpatialRotate,\n onSpatialRotateEnd,\n onSpatialMagnify,\n onSpatialMagnifyEnd,\n }\n}\n\nexport function useSpatialEvents<T extends SpatializedElementRef>(\n spatialEvents: SpatialEvents<T>,\n spatialContainerRefProxy: RefObject<SpatialContainerRefProxy<T>>,\n) {\n return useSpatialEventsBase<T>(\n spatialEvents,\n () => spatialContainerRefProxy.current?.domProxy!,\n )\n}\n\nexport function useSpatialEventsWhenSpatializedContainerExist<\n T extends SpatializedElementRef,\n>(\n spatialEvents: SpatialEvents<T>,\n spatialId: string,\n spatializedContainerObject: SpatializedContainerObject<T>,\n) {\n return useSpatialEventsBase<T>(spatialEvents, () => {\n const spatialContainerRefProxy =\n spatializedContainerObject.getSpatialContainerRefProxyBySpatialId(\n spatialId,\n )\n return spatialContainerRefProxy?.domProxy as T\n })\n}\n","import { createPortal } from 'react-dom'\nimport React, {\n CSSProperties,\n ElementType,\n ForwardedRef,\n forwardRef,\n useCallback,\n useEffect,\n useState,\n} from 'react'\n\nimport { Spatialized2DElement } from '@webspatial/core-sdk'\n\nimport {\n setOpenWindowStyle,\n syncParentHeadToChild,\n} from '../utils/windowStyleSync'\nimport { useSyncHeadStyles } from '../utils/useSyncHeadStyles'\nimport { getInheritedStyleProps, parseCornerRadius } from './utils'\nimport {\n SpatialCustomStyleVars,\n Spatialized2DElementContainerProps,\n SpatializedElementRef,\n SpatializedContentProps,\n SpatializedDivElementRef,\n} from './types'\nimport { SpatializedContainer } from './SpatializedContainer'\nimport type { PortalInstanceObject } from './context/PortalInstanceContext'\nimport { getSession } from '../utils'\nimport { detectSpatialRuntime } from '../runtime/detect'\nimport { useSpatialContentReady } from './hooks/useSpatialContentReady'\n\nfunction mergeRefs<T>(\n ...refs: Array<React.Ref<T> | undefined | null>\n): React.RefCallback<T> {\n return value => {\n for (const ref of refs) {\n if (ref == null) continue\n if (typeof ref === 'function') {\n ref(value)\n } else {\n ;(ref as React.MutableRefObject<T | null>).current = value\n }\n }\n }\n}\n\nfunction getJSXPortalInstance<P extends ElementType>(\n inProps: Omit<\n SpatializedContentProps<SpatializedElementRef, P>,\n 'spatializedElement' | 'onSpatialContentReady' | 'portalInstanceObject'\n >,\n portalInstanceObject: PortalInstanceObject,\n hostRef?: React.RefCallback<HTMLElement | null>,\n) {\n const {\n component: El,\n style: inStyle = {},\n ref: userRef,\n ...props\n } = inProps as React.ComponentPropsWithRef<P> & {\n component: P\n }\n const isVisionOSRuntime = detectSpatialRuntime() === 'visionos'\n const extraStyle: CSSProperties = {\n visibility: 'visible',\n position: 'relative',\n top: '0px',\n left: '0px',\n margin: '0px',\n marginLeft: '0px',\n marginRight: '0px',\n marginTop: '0px',\n marginBottom: '0px',\n borderRadius: '0px',\n ...(isVisionOSRuntime\n ? {\n // Root opacity remains native-owned on the spatial host, not the portal DOM.\n opacity: 1,\n }\n : {}),\n // overflow: '',\n transform: 'none',\n }\n\n const computedStyle = portalInstanceObject.computedStyle\n const inheritedPortalStyle: CSSProperties = computedStyle\n ? getInheritedStyleProps(computedStyle)\n : {}\n\n const style = {\n ...inStyle,\n ...inheritedPortalStyle,\n ...extraStyle,\n }\n\n const mergedRef = hostRef != null ? mergeRefs(hostRef, userRef) : userRef\n\n return <El ref={mergedRef} style={style} {...props} />\n}\n\nfunction useSyncDocumentTitle(\n windowProxy: WindowProxy,\n spatializedElement: Spatialized2DElement,\n name: string,\n) {\n useEffect(() => {\n windowProxy.document.title = name\n spatializedElement.updateProperties({\n name,\n })\n }, [name])\n}\n\nfunction SpatializedContent<P extends ElementType>(\n props: SpatializedContentProps<SpatializedElementRef, P>,\n) {\n const {\n spatializedElement,\n portalInstanceObject,\n onSpatialContentReady,\n ...restProps\n } = props\n const spatialized2DElement = spatializedElement as Spatialized2DElement\n const { windowProxy } = spatialized2DElement\n\n const [hostEl, setHostEl] = useState<HTMLElement | null>(null)\n\n useSpatialContentReady({\n spatializedElement,\n portalInstanceObject,\n hostElement: hostEl,\n onSpatialContentReady,\n })\n\n useSyncHeadStyles(windowProxy)\n\n const name: string = (restProps as any)['data-name'] || ''\n useSyncDocumentTitle(windowProxy, spatialized2DElement, name)\n\n const setHostCallback = useCallback((el: HTMLElement | null) => {\n setHostEl(el)\n }, [])\n\n const JSXPortalInstance = getJSXPortalInstance(\n restProps,\n portalInstanceObject,\n setHostCallback,\n )\n\n return createPortal(JSXPortalInstance, windowProxy.document.body)\n}\n\nfunction getExtraSpatializedElementProperties(\n computedStyle: CSSStyleDeclaration,\n) {\n // get extra spatialized element properties for Spatialized2DElement\n const overflow = computedStyle.getPropertyValue('overflow')\n const scrollPageEnabled = ['visible', 'hidden', 'clip'].indexOf(overflow) >= 0\n const material = computedStyle.getPropertyValue(\n SpatialCustomStyleVars.backgroundMaterial,\n )\n\n const properties: Record<string, any> = {}\n properties.scrollPageEnabled = scrollPageEnabled\n properties.cornerRadius = parseCornerRadius(computedStyle)\n if (material) {\n properties.material = material\n }\n\n // may need add scrollEdgeInsetsMarginRight in future\n return properties\n}\n\nasync function createSpatializedElement() {\n const spatializedElement = await getSession()!.createSpatialized2DElement()\n const { windowProxy } = spatializedElement\n setOpenWindowStyle(windowProxy)\n await syncParentHeadToChild(windowProxy)\n\n const viewport = windowProxy.document.querySelector('meta[name=\"viewport\"]')\n if (viewport) {\n viewport?.setAttribute(\n 'content',\n ' initial-scale=1.0, maximum-scale=1.0, user-scalable=no',\n )\n } else {\n const meta = windowProxy.document.createElement('meta')\n meta.name = 'viewport'\n meta.content = 'initial-scale=1.0, maximum-scale=1.0, user-scalable=no'\n windowProxy.document.head.appendChild(meta)\n }\n\n return spatializedElement\n}\n\nfunction Spatialized2DElementContainerBase<P extends ElementType>(\n props: Spatialized2DElementContainerProps<P>,\n ref: ForwardedRef<SpatializedDivElementRef>,\n) {\n return (\n <SpatializedContainer<SpatializedElementRef>\n ref={ref as any}\n createSpatializedElement={createSpatializedElement}\n getExtraSpatializedElementProperties={\n getExtraSpatializedElementProperties\n }\n spatializedContent={SpatializedContent}\n {...props}\n />\n )\n}\n\nexport const Spatialized2DElementContainer = forwardRef(\n Spatialized2DElementContainerBase,\n) as <P extends ElementType>(\n props: Spatialized2DElementContainerProps<P> & {\n ref: ForwardedRef<SpatializedElementRef>\n },\n) => React.ReactElement | null\n","import { useEffect } from 'react'\n\nimport {\n disposeSyncParentHeadToChild,\n registerParentHeadSyncTarget,\n} from './windowStyleSync'\n\nexport function useSyncHeadStyles(childWindow: WindowProxy | null | undefined) {\n useEffect(() => {\n if (!childWindow) return\n\n const unregister = registerParentHeadSyncTarget(childWindow)\n\n return () => {\n unregister()\n disposeSyncParentHeadToChild(childWindow)\n }\n }, [childWindow])\n}\n","import { useLayoutEffect, useRef } from 'react'\nimport type { SpatializedElement } from '@webspatial/core-sdk'\nimport type { SpatialContentReadyCallback } from '../types'\nimport type { PortalInstanceObject } from '../context/PortalInstanceContext'\n\nconst isDev = process.env.NODE_ENV !== 'production'\n\nfunction safeInvokeCleanup(cleanup: (() => void) | undefined) {\n if (!cleanup) return\n try {\n cleanup()\n } catch (e) {\n if (isDev) {\n console.error('[WebSpatial] onSpatialContentReady cleanup threw', e)\n }\n }\n}\n\n/**\n * Edge-triggered portal readiness for `onSpatialContentReady`: fires once per rising edge\n * (`false → true`) in useLayoutEffect timing; cleanup runs from the layout-effect dispose\n * path (falling edge, deps change, unmount).\n */\nexport function useSpatialContentReady(params: {\n spatializedElement: SpatializedElement | undefined\n /** May be null during HMR teardown or before PortalInstanceContext is mounted. */\n portalInstanceObject: PortalInstanceObject | null\n /** Portal subtree root element (connected when ready). */\n hostElement: HTMLElement | null\n onSpatialContentReady?: SpatialContentReadyCallback | undefined\n}) {\n const {\n spatializedElement,\n portalInstanceObject,\n hostElement,\n onSpatialContentReady,\n } = params\n\n const callbackRef = useRef(onSpatialContentReady)\n callbackRef.current = onSpatialContentReady\n const portalDom = portalInstanceObject?.dom\n\n useLayoutEffect(() => {\n const isReady = !!(\n spatializedElement &&\n portalDom &&\n hostElement &&\n hostElement.isConnected\n )\n\n if (!isReady || !hostElement) {\n return () => {}\n }\n\n const cb = callbackRef.current\n let cleanupFromCallback: (() => void) | undefined\n\n if (cb) {\n try {\n const ret = cb({ host: hostElement })\n cleanupFromCallback = typeof ret === 'function' ? ret : undefined\n } catch (e) {\n if (isDev) {\n console.error('[WebSpatial] onSpatialContentReady threw', e)\n }\n }\n }\n\n return () => {\n safeInvokeCleanup(cleanupFromCallback)\n }\n }, [spatializedElement, portalDom, hostElement])\n}\n","import {\n Children,\n ForwardedRef,\n forwardRef,\n isValidElement,\n ReactElement,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n} from 'react'\nimport { SpatializedContainer } from './SpatializedContainer'\nimport { getSession } from '../utils'\nimport {\n ModelLoadEvent,\n SpatializedStatic3DContainerProps,\n SpatializedStatic3DContentProps,\n SpatializedStatic3DElementRef,\n} from './types'\nimport { ModelSource, SpatializedStatic3DElement } from '@webspatial/core-sdk'\nimport { PortalInstanceContext } from './context/PortalInstanceContext'\n\nfunction getAbsoluteURL(url: string): string\nfunction getAbsoluteURL(url: undefined): undefined\nfunction getAbsoluteURL(url: string | undefined): string | undefined\nfunction getAbsoluteURL(url?: string) {\n if (!url) return url\n try {\n return new URL(url, document.baseURI).toString()\n } catch {\n return url\n }\n}\n\nfunction createLoadEvent(\n type: string,\n targetGetter: () => SpatializedStatic3DElementRef,\n): ModelLoadEvent {\n const event = new CustomEvent(type, {\n bubbles: false,\n cancelable: false,\n })\n const proxyEvent = new Proxy(event, {\n get(target, prop) {\n if (prop === 'target' || prop === 'currentTarget') {\n return targetGetter()\n }\n return Reflect.get(target, prop)\n },\n })\n return proxyEvent as ModelLoadEvent\n}\n\nfunction createLoadFailureEvent(\n targetGetter: () => SpatializedStatic3DElementRef,\n): ModelLoadEvent {\n return createLoadEvent('modelloadfailed', targetGetter)\n}\n\nfunction createLoadSuccessEvent(\n targetGetter: () => SpatializedStatic3DElementRef,\n): ModelLoadEvent {\n return createLoadEvent('modelloaded', targetGetter)\n}\n\nfunction collectSources(children: React.ReactNode): ModelSource[] {\n const sources: ModelSource[] = []\n Children.forEach(children, child => {\n if (\n isValidElement(child) &&\n (child as ReactElement<{ src?: string; type?: string }>).type === 'source'\n ) {\n const { src, type } = (\n child as ReactElement<{ src?: string; type?: string }>\n ).props\n if (src) {\n sources.push({ src: getAbsoluteURL(src), type })\n }\n }\n })\n return sources\n}\n\ntype Static3DDomProxy = SpatializedStatic3DElementRef & {\n __spatializedElement?: SpatializedStatic3DElement\n __innerSpatializedElement?: () => SpatializedStatic3DElement | undefined\n}\n\nfunction getDomSpatializedStaticElement(\n domProxy: SpatializedStatic3DElementRef,\n): SpatializedStatic3DElement | undefined {\n const proxy = domProxy as Static3DDomProxy\n // Nested standard branches expose the DOM/ref while the portal branch owns\n // the actual static 3D element, so resolve through either DOM binding.\n return proxy.__spatializedElement ?? proxy.__innerSpatializedElement?.()\n}\n\nfunction SpatializedContent(props: SpatializedStatic3DContentProps) {\n const {\n src,\n poster,\n children,\n spatializedElement,\n onLoad,\n onError,\n autoPlay,\n loop,\n loading = 'eager',\n stagemode = 'none',\n } = props\n const portalInstanceObject = useContext(PortalInstanceContext)\n const wasVisible = useRef(false)\n\n const modelURL = useMemo(() => getAbsoluteURL(src), [src])\n const posterURL = useMemo(() => getAbsoluteURL(poster), [poster])\n const sources = useMemo(() => collectSources(children), [children])\n const sourcesKey = useMemo(() => JSON.stringify(sources), [sources])\n\n // Observe when model becomes visible and then stop until sources change\n useEffect(() => {\n const target = portalInstanceObject?.dom\n wasVisible.current = false\n if (loading !== 'lazy') {\n wasVisible.current = true\n return\n }\n if (!target) {\n return\n }\n if (typeof IntersectionObserver === 'undefined') {\n wasVisible.current = true\n spatializedElement.updateProperties({ loading: 'eager' })\n return\n }\n const observer = new IntersectionObserver(entries => {\n if (entries.some(entry => entry.isIntersecting)) {\n wasVisible.current = true\n observer.disconnect()\n spatializedElement.updateProperties({ loading: 'eager' })\n }\n })\n observer.observe(target)\n return () => observer.disconnect()\n }, [modelURL, sourcesKey, portalInstanceObject?.dom])\n\n useEffect(() => {\n if (loading !== 'lazy') wasVisible.current = true\n // If modelURL was previously set and now is undefined then a dummy\n // value needs to be sent to clear the old value\n // TODO: Can native side handle null instead of ''\n spatializedElement.updateProperties({\n modelURL: modelURL ?? (spatializedElement.modelUrl ? '' : modelURL),\n sources,\n autoplay: autoPlay,\n loop,\n posterURL: posterURL ?? '',\n loading: loading === 'lazy' && wasVisible.current ? 'eager' : loading,\n stagemode,\n })\n }, [modelURL, sourcesKey, autoPlay, loop, posterURL, loading, stagemode])\n\n useEffect(() => {\n const dom = portalInstanceObject?.dom\n if (onLoad && dom) {\n spatializedElement.onLoadCallback = () => {\n onLoad(\n createLoadSuccessEvent(() => dom as SpatializedStatic3DElementRef),\n )\n }\n } else {\n spatializedElement.onLoadCallback = undefined\n }\n }, [onLoad, portalInstanceObject?.dom])\n\n useEffect(() => {\n const dom = portalInstanceObject?.dom\n if (onError && dom) {\n spatializedElement.onLoadFailureCallback = () => {\n onError(\n createLoadFailureEvent(() => dom as SpatializedStatic3DElementRef),\n )\n }\n } else {\n spatializedElement.onLoadFailureCallback = undefined\n }\n }, [onError, portalInstanceObject?.dom])\n\n return <></>\n}\n\nfunction SpatializedStatic3DElementContainerBase(\n props: SpatializedStatic3DContainerProps,\n ref: ForwardedRef<SpatializedStatic3DElementRef>,\n) {\n const promiseRef = useRef<Promise<SpatializedStatic3DElement> | null>(null)\n\n const createSpatializedElement = useCallback(() => {\n promiseRef.current = getSession()!.createSpatializedStatic3DElement(\n getAbsoluteURL(props.src),\n collectSources(props.children),\n props.loading === 'lazy' ? 'lazy' : 'eager',\n )\n return promiseRef.current\n }, [])\n const extraRefProps = useCallback(\n (domProxy: SpatializedStatic3DElementRef) => {\n return {\n get currentSrc(): string {\n const spatializedElement = getDomSpatializedStaticElement(domProxy)\n return spatializedElement?.currentSrc ?? ''\n },\n get ready(): Promise<ModelLoadEvent> {\n const spatializedElement = getDomSpatializedStaticElement(domProxy)\n const readySource = spatializedElement\n ? Promise.resolve(spatializedElement)\n : promiseRef.current\n if (!readySource) {\n return Promise.reject(createLoadFailureEvent(() => domProxy))\n }\n return readySource\n .then(element => element.ready)\n .then(success => {\n if (success) return createLoadSuccessEvent(() => domProxy)\n throw createLoadFailureEvent(() => domProxy)\n })\n },\n get entityTransform(): DOMMatrixReadOnly {\n const spatializedElement = getDomSpatializedStaticElement(domProxy)\n return spatializedElement?.entityTransform ?? new DOMMatrixReadOnly()\n },\n set entityTransform(value: DOMMatrixReadOnly) {\n const spatializedElement = getDomSpatializedStaticElement(domProxy)\n if (spatializedElement) {\n spatializedElement.entityTransform = value\n }\n },\n async play(): Promise<void> {\n const spatializedElement = getDomSpatializedStaticElement(domProxy)\n await spatializedElement?.play()\n },\n async pause(): Promise<void> {\n const spatializedElement = getDomSpatializedStaticElement(domProxy)\n await spatializedElement?.pause()\n },\n get paused(): boolean {\n const spatializedElement = getDomSpatializedStaticElement(domProxy)\n return spatializedElement?.paused ?? true\n },\n get duration(): number {\n const spatializedElement = getDomSpatializedStaticElement(domProxy)\n return spatializedElement?.duration ?? 0\n },\n get playbackRate(): number {\n const spatializedElement = getDomSpatializedStaticElement(domProxy)\n return spatializedElement?.playbackRate ?? 1\n },\n set playbackRate(value: number) {\n const spatializedElement = getDomSpatializedStaticElement(domProxy)\n if (spatializedElement) {\n spatializedElement.playbackRate = value\n }\n },\n get currentTime(): number {\n const spatializedElement = getDomSpatializedStaticElement(domProxy)\n return spatializedElement?.currentTime ?? 0\n },\n set currentTime(value: number) {\n const spatializedElement = getDomSpatializedStaticElement(domProxy)\n if (spatializedElement) {\n spatializedElement.currentTime = value\n }\n },\n }\n },\n [],\n )\n\n return (\n <SpatializedContainer<SpatializedStatic3DElementRef>\n ref={ref}\n component=\"div\"\n createSpatializedElement={createSpatializedElement}\n spatializedContent={SpatializedContent}\n extraRefProps={extraRefProps}\n {...props}\n />\n )\n}\n\nexport const SpatializedStatic3DElementContainer = forwardRef(\n SpatializedStatic3DElementContainerBase,\n)\n","import { ElementType, ForwardedRef, forwardRef } from 'react'\nimport { Spatialized2DElementContainer } from './Spatialized2DElementContainer'\nimport {\n Spatialized2DElementContainerProps,\n SpatializedElementRef,\n} from './types'\n\nconst CachedSpatialized2DElementContainerType = new Map()\n\nexport function withSpatialized2DElementContainer<P extends ElementType>(\n Component: P,\n) {\n if (CachedSpatialized2DElementContainerType.has(Component)) {\n return CachedSpatialized2DElementContainerType.get(Component) as P\n } else {\n const TypedSpatialized2DElementContainer = forwardRef(\n (\n givenProps: Spatialized2DElementContainerProps<P>,\n ref: ForwardedRef<SpatializedElementRef>,\n ) => {\n const { component: ignoreComponent, ...props } = givenProps\n return (\n <Spatialized2DElementContainer<P>\n component={Component}\n {...props}\n ref={ref as any}\n />\n )\n },\n )\n\n CachedSpatialized2DElementContainerType.set(\n Component,\n TypedSpatialized2DElementContainer,\n )\n CachedSpatialized2DElementContainerType.set(\n TypedSpatialized2DElementContainer,\n TypedSpatialized2DElementContainer,\n )\n return TypedSpatialized2DElementContainer\n }\n}\n","import { useEffect, useMemo, useReducer, useRef } from 'react'\nimport type { CSSProperties } from 'react'\nimport type {\n SpatializedMotionConfig as CoreSpatializedMotionConfig,\n SpatializedMotionSegmentConfig as CoreSpatializedMotionSegmentConfig,\n SpatializedPlaybackApi,\n SpatializedVisualValues,\n} from '@webspatial/core-sdk'\nimport { getMotionConfigSignature } from './motionConfigSignature'\nimport type { SpatializedMotionBinding } from './motionBindingTypes'\nimport { AnimationBinding } from './AnimationBinding'\nimport { valuesToMotionStyle } from './style'\n\n/**\n * React-facing motion config accepted by `useAnimation()`.\n */\nexport type SpatializedMotionConfig = CoreSpatializedMotionConfig\n\n/** Convenience alias for the segment-style authoring shape. */\nexport type SpatializedMotionSegmentConfig = CoreSpatializedMotionSegmentConfig\n\n/**\n * Tuple returned by `useAnimation()`.\n */\nexport type UseAnimationResult = readonly [\n animation: SpatializedMotionBinding,\n api: SpatializedPlaybackApi,\n style: CSSProperties,\n]\n\n/**\n * Creates the target-agnostic spatialized motion tuple used by React\n * containers.\n *\n * @param config - The motion config to normalize and bind to a controller.\n * @returns The opaque binding, playback api, and React style outlet.\n */\nexport function useAnimation(\n config: SpatializedMotionConfig,\n): UseAnimationResult {\n const dataSignature = getMotionConfigSignature(config)\n const [, forceRender] = useReducer((n: number) => n + 1, 0)\n const bindingRef = useRef<AnimationBinding | null>(null)\n const destroyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)\n\n if (!bindingRef.current) {\n bindingRef.current = new AnimationBinding(config, {\n onValuesChange: () => forceRender(),\n onStateChange: () => forceRender(),\n })\n }\n\n const binding = bindingRef.current\n\n useEffect(() => {\n binding.updateConfig(config)\n }, [binding, config, dataSignature])\n\n useEffect(() => {\n if (destroyTimerRef.current) {\n clearTimeout(destroyTimerRef.current)\n destroyTimerRef.current = null\n }\n return () => {\n const bindingToDestroy = binding\n destroyTimerRef.current = setTimeout(() => {\n if (bindingRef.current === bindingToDestroy) {\n bindingToDestroy.destroy()\n bindingRef.current = null\n }\n destroyTimerRef.current = null\n }, 0)\n }\n }, [binding])\n\n const api = useMemo(\n () => ({\n play: () => binding.play(),\n pause: () => binding.pause(),\n stop: () => binding.stop(),\n reset: () => binding.reset(),\n finish: () => binding.finish(),\n get isAnimating() {\n return binding.isAnimating\n },\n get isPaused() {\n return binding.isPaused\n },\n get finished() {\n return binding.finished\n },\n get playState() {\n return binding.playState\n },\n }),\n [binding],\n )\n\n const values: SpatializedVisualValues = binding.currentValues\n const style = valuesToMotionStyle(values)\n\n return [binding, api, style]\n}\n\nexport type { SpatializedPlaybackApi as SpatializedPlaybackApi }\n","import type { SpatializedMotionConfig } from '@webspatial/core-sdk'\n\n// Ignore callback identity so visual state does not reset on every render.\nexport function getMotionConfigSignature(\n config: SpatializedMotionConfig,\n): string {\n const effectiveConfig =\n config.timeline !== undefined\n ? { ...config, from: undefined, to: undefined }\n : config\n return JSON.stringify(effectiveConfig, (_key, value) =>\n typeof value === 'function' ? undefined : value,\n )\n}\n","import type {\n SpatializedElement,\n SpatializedMotionConfig,\n SpatializedMotionKind,\n SpatializedMotionPlayState,\n SpatializedPlaybackApi,\n SpatializedPlaybackError,\n SpatializedVisualValues,\n} from '@webspatial/core-sdk'\nimport { supports, validateSpatializedMotionConfig } from '@webspatial/core-sdk'\nimport { getMotionConfigSignature } from './motionConfigSignature'\n\n/** Internal animation object returned by a spatialized element. */\ntype AnimationObject = Awaited<\n ReturnType<SpatializedElement['createAnimation']>\n>\n\ntype AnimationCommandType = 'play' | 'pause' | 'stop' | 'reset' | 'finish'\n\ntype AnimationCommand = {\n type: AnimationCommandType\n}\n\ninterface AnimationBindingOptions {\n onValuesChange?: (values: SpatializedVisualValues) => void\n onStateChange?: () => void\n}\n\nfunction supportsAnimation(): boolean {\n return supports('useAnimation')\n}\n\n/**\n * React-owned binding for spatialized motion.\n */\nexport class AnimationBinding implements SpatializedPlaybackApi {\n readonly __kind = 'spatializedMotion' as const\n\n private animationObject: AnimationObject | null = null\n private element: SpatializedElement | null = null\n private destroyed = false\n private creating = false\n private createToken = 0\n private pendingCommands: AnimationCommand[] = []\n private configSignature: string\n private config: SpatializedMotionConfig\n private values: SpatializedVisualValues\n private state: SpatializedMotionPlayState = 'idle'\n private isAnimatingState = false\n private isPausedState = false\n private finishedState = false\n private readonly options: AnimationBindingOptions\n\n constructor(\n config: SpatializedMotionConfig,\n options: AnimationBindingOptions = {},\n ) {\n validateSpatializedMotionConfig(config)\n this.options = options\n this.config = config\n this.configSignature = getMotionConfigSignature(config)\n // Keep the fallback snapshot empty after removing timeline sampling utilities.\n this.values = {}\n }\n\n get configSnapshot(): SpatializedMotionConfig {\n return this.config\n }\n\n get currentValues(): SpatializedVisualValues {\n return this.values\n }\n\n get targetKind(): SpatializedMotionKind | null {\n return this.element?.kind ?? null\n }\n\n get playState(): SpatializedMotionPlayState {\n if (this.animationObject) return this.animationObject.playState\n if (this.pendingCommands.length > 0) return 'queued'\n return this.state\n }\n\n get isAnimating(): boolean {\n if (this.animationObject) return this.animationObject.isAnimating\n return this.isAnimatingState\n }\n\n get isPaused(): boolean {\n if (this.animationObject) return this.animationObject.isPaused\n return this.isPausedState\n }\n\n get finished(): boolean {\n if (this.animationObject) return this.animationObject.finished\n return this.finishedState\n }\n\n __setElement(element: SpatializedElement | null): void {\n this.bind(element)\n }\n\n __onUnbind(element: SpatializedElement): void {\n this.unbind(element)\n }\n\n play(): void {\n this.dispatchCommand({ type: 'play' })\n }\n\n pause(): void {\n this.dispatchCommand({ type: 'pause' })\n }\n\n stop(): void {\n this.dispatchCommand({ type: 'stop' })\n }\n\n reset(): void {\n this.dispatchCommand({ type: 'reset' })\n }\n\n finish(): void {\n this.dispatchCommand({ type: 'finish' })\n }\n\n updateConfig(config: SpatializedMotionConfig): void {\n validateSpatializedMotionConfig(config)\n const nextSignature = getMotionConfigSignature(config)\n // Preserve callback ownership for the AnimationObject being replaced.\n const previousConfig = this.config\n this.config = config\n if (nextSignature !== this.configSignature) {\n this.configSignature = nextSignature\n this.recreateAnimationObject(previousConfig)\n } else if (this.animationObject) {\n this.animationObject.setCallbacks(\n this.createAnimationObjectCallbacks(this.animationObject),\n )\n }\n }\n\n destroy(): void {\n this.destroyed = true\n this.pendingCommands = []\n this.detachAnimationObject()\n this.element = null\n this.options.onStateChange?.()\n }\n\n private bind(element: SpatializedElement | null): void {\n if (this.destroyed) return\n if (!element) {\n this.unbind()\n return\n }\n if (this.element && this.element !== element) {\n console.warn(\n '[AnimationBinding] motion binding already attached to another component; ignoring subsequent bind.',\n )\n return\n }\n validateSpatializedMotionConfig(this.config)\n this.element = element\n this.ensureAnimationObject()\n this.options.onStateChange?.()\n }\n\n private unbind(element?: SpatializedElement): void {\n if (this.destroyed) return\n if (element && this.element !== element) return\n this.detachAnimationObject()\n this.element = null\n this.options.onStateChange?.()\n }\n\n private detachAnimationObject(config = this.config): void {\n const object = this.animationObject\n const onError = config.onError\n this.animationObject = null\n this.createToken += 1\n this.creating = false\n object?.destroy().catch(error => {\n onError?.({\n command: 'destroy',\n reason: error instanceof Error ? error.message : 'Destroy failed',\n })\n })\n this.state = 'idle'\n this.isAnimatingState = false\n this.isPausedState = false\n this.finishedState = false\n }\n\n private recreateAnimationObject(detachedConfig = this.config): void {\n const element = this.element\n this.detachAnimationObject(detachedConfig)\n if (element && supportsAnimation()) {\n this.ensureAnimationObject()\n return\n }\n // Keep the fallback snapshot empty after removing timeline sampling utilities.\n this.values = {}\n this.options.onValuesChange?.(this.values)\n this.options.onStateChange?.()\n }\n\n private ensureAnimationObject(): void {\n if (this.animationObject || this.creating || !this.element) {\n return\n }\n if (!supportsAnimation()) {\n return\n }\n const token = ++this.createToken\n const element = this.element\n const kind = element.kind\n\n this.creating = true\n element\n .createAnimation(this.config)\n .then(async animationObject => {\n if (\n this.destroyed ||\n token !== this.createToken ||\n this.element !== element ||\n this.element.kind !== kind\n ) {\n animationObject.destroy().catch(() => {})\n return\n }\n\n this.animationObject = animationObject\n this.creating = false\n animationObject.setCallbacks(\n this.createAnimationObjectCallbacks(animationObject),\n )\n this.syncStateFromAnimationObject()\n if (this.config.autoStart !== false) {\n this.pendingCommands.unshift({ type: 'play' })\n }\n await this.flushPendingCommands()\n if (\n this.destroyed ||\n token !== this.createToken ||\n this.animationObject !== animationObject ||\n this.element !== element ||\n this.element.kind !== kind\n ) {\n return\n }\n this.options.onStateChange?.()\n })\n .catch(error => {\n if (token !== this.createToken) return\n this.creating = false\n this.pendingCommands = []\n this.state = 'idle'\n this.isAnimatingState = false\n this.isPausedState = false\n this.finishedState = false\n this.config.onError?.({\n command: 'create',\n reason: error instanceof Error ? error.message : 'Create failed',\n })\n this.options.onStateChange?.()\n })\n }\n\n private createAnimationObjectCallbacks(animationObject: AnimationObject) {\n // Ignore delayed callbacks after unbind or animation object replacement.\n const isCurrent = () =>\n !this.destroyed && this.animationObject === animationObject\n return {\n onStart: () => {\n if (!isCurrent()) return\n this.config.onStart?.()\n },\n onComplete: (values: SpatializedVisualValues) => {\n if (!isCurrent()) return\n this.config.onComplete?.(values)\n },\n onStop: (values: SpatializedVisualValues) => {\n if (!isCurrent()) return\n this.config.onStop?.(values)\n },\n onReset: (values: SpatializedVisualValues) => {\n if (!isCurrent()) return\n this.config.onReset?.(values)\n },\n onError: (error: SpatializedPlaybackError) => {\n if (!isCurrent()) return\n this.config.onError?.(error)\n },\n onValuesChange: (values: SpatializedVisualValues) => {\n if (!isCurrent()) return\n this.values = values\n this.options.onValuesChange?.(values)\n },\n onStateChange: () => {\n if (!isCurrent()) return\n this.syncStateFromAnimationObject()\n this.options.onStateChange?.()\n },\n }\n }\n\n private syncStateFromAnimationObject(): void {\n if (!this.animationObject) return\n this.state = this.animationObject.playState\n this.isAnimatingState = this.animationObject.isAnimating\n this.isPausedState = this.animationObject.isPaused\n this.finishedState = this.animationObject.finished\n }\n\n private dispatchCommand(command: AnimationCommand): void {\n if (this.destroyed) return\n if (!this.animationObject || !this.element) {\n this.pendingCommands.push(command)\n this.applyQueuedState(command)\n this.options.onStateChange?.()\n return\n }\n this.animationObject[command.type]().catch(error => {\n this.config.onError?.({\n command: command.type,\n reason: error instanceof Error ? error.message : 'Command failed',\n })\n })\n this.syncStateFromAnimationObject()\n this.options.onStateChange?.()\n }\n\n private applyQueuedState(command: AnimationCommand): void {\n switch (command.type) {\n case 'play':\n this.state = 'queued'\n this.isAnimatingState = true\n this.isPausedState = false\n this.finishedState = false\n break\n case 'pause':\n this.state = 'queued'\n this.isAnimatingState = false\n this.isPausedState = true\n break\n case 'stop':\n case 'reset':\n case 'finish':\n this.state = 'queued'\n this.isAnimatingState = false\n this.isPausedState = false\n this.finishedState = false\n break\n }\n }\n\n private async flushPendingCommands(): Promise<void> {\n if (!this.animationObject || !this.element) return\n const animationObject = this.animationObject\n const commands = this.pendingCommands\n this.pendingCommands = []\n for (const command of commands) {\n try {\n await animationObject[command.type]()\n } catch (error) {\n this.config.onError?.({\n command: command.type,\n reason: error instanceof Error ? error.message : 'Command failed',\n })\n }\n if (\n this.destroyed ||\n this.animationObject !== animationObject ||\n !this.element\n ) {\n return\n }\n }\n this.syncStateFromAnimationObject()\n }\n}\n","import type { CSSProperties } from 'react'\nimport type { SpatializedVisualValues } from '@webspatial/core-sdk'\n\n/** Convert evaluated values to React style for SpatialDiv host/probe. */\nexport function valuesToMotionStyle(\n values: SpatializedVisualValues,\n): CSSProperties {\n const style: CSSProperties = {}\n\n if (values.opacity !== undefined) {\n style.opacity = values.opacity\n }\n\n const t = values.transform\n if (t) {\n const parts: string[] = []\n const tr = t.translate\n if (\n tr &&\n (tr.x !== undefined || tr.y !== undefined || tr.z !== undefined)\n ) {\n parts.push(`translate3d(${tr.x ?? 0}px, ${tr.y ?? 0}px, ${tr.z ?? 0}px)`)\n }\n const rot = t.rotate\n if (rot) {\n if (rot.z !== undefined) parts.push(`rotateZ(${rot.z}deg)`)\n if (rot.y !== undefined) parts.push(`rotateY(${rot.y}deg)`)\n if (rot.x !== undefined) parts.push(`rotateX(${rot.x}deg)`)\n }\n const sc = t.scale\n if (sc) {\n if (sc.x !== undefined) parts.push(`scaleX(${sc.x})`)\n if (sc.y !== undefined) parts.push(`scaleY(${sc.y})`)\n if (sc.z !== undefined) parts.push(`scaleZ(${sc.z})`)\n }\n if (parts.length > 0) {\n style.transform = parts.join(' ')\n }\n }\n\n return style\n}\n","import { injectSpatialDefaultStyle } from './StandardSpatializedContainer'\nimport { initCSSParserDivContainer } from './TransformVisibilityTaskContainer'\n\nexport { SpatializedContainer } from './SpatializedContainer'\nexport { Spatialized2DElementContainer } from './Spatialized2DElementContainer'\nexport { SpatializedStatic3DElementContainer } from './SpatializedStatic3DElementContainer'\nexport { withSpatialized2DElementContainer } from './Spatialized2DElementContainerFactory'\nexport { useAnimation } from './motion'\nexport {\n type Point3D,\n type Vec3,\n type SpatializedElementRef,\n type SpatialTapEvent,\n type SpatialDragStartEvent,\n type SpatialDragEvent,\n type SpatialDragEndEvent,\n type SpatialRotateEvent,\n type SpatialRotateEndEvent,\n type SpatialMagnifyEvent,\n type SpatialMagnifyEndEvent,\n type SpatializedStatic3DContainerProps,\n type Spatialized2DElementContainerProps,\n type SpatializedStatic3DElementRef,\n type ModelSpatialTapEvent,\n type ModelSpatialDragStartEvent,\n type ModelSpatialDragEvent,\n type ModelSpatialDragEndEvent,\n type ModelSpatialRotateEvent,\n type ModelSpatialRotateEndEvent,\n type ModelSpatialMagnifyEvent,\n type ModelSpatialMagnifyEndEvent,\n type ModelLoadEvent,\n type SpatialEventOptions,\n type SpatialContentReadyContext,\n type SpatialContentReadyCallback,\n} from './types'\n\nexport function initPolyfill() {\n injectSpatialDefaultStyle()\n initCSSParserDivContainer()\n}\n","import { ForwardedRef, forwardRef } from 'react'\nimport {\n SpatializedStatic3DContainerProps,\n SpatializedStatic3DElementContainer,\n SpatializedStatic3DElementRef,\n} from './spatialized-container'\nimport { useInsideAttachment } from './reality/context/InsideAttachmentContext'\nimport { markWebSpatialPrimitive } from './jsx/primitive-marker'\n\nimport { Spatial } from '@webspatial/core-sdk'\n\nexport type ModelProps = SpatializedStatic3DContainerProps & {\n 'enable-xr'?: boolean\n}\n\nexport type ModelRef = SpatializedStatic3DElementRef\n\nconst spatial = new Spatial()\n\nfunction ModelBase(props: ModelProps, ref: ForwardedRef<ModelRef>) {\n const insideAttachment = useInsideAttachment()\n const { 'enable-xr': enableXR, ...restProps } = props\n // Model must handle insideAttachment itself because\n // SpatializedStatic3DElementContainer passes component=\"div\" to the base,\n // but the correct degraded element for a Model is a <model> tag, not a <div>.\n if (!enableXR || !spatial.runInSpatialWeb() || insideAttachment) {\n const {\n onSpatialTap,\n onSpatialDragStart,\n onSpatialDrag,\n onSpatialDragEnd,\n onSpatialRotate,\n onSpatialRotateEnd,\n onSpatialMagnify,\n onSpatialMagnifyEnd,\n spatialEventOptions: _spatialEventOptions,\n 'xr-animation': _xrAnimation,\n ...modelProps\n } = restProps\n void _xrAnimation\n // map to VisionOS26 model tag outside attachments\n // @ts-ignore\n return <model ref={ref} {...modelProps} />\n }\n\n // In orbit mode the native layer drives the model's transform, so the\n // `onSpatial*` gesture handlers are disabled.\n if (restProps.stagemode === 'orbit') {\n const {\n onSpatialTap,\n onSpatialDragStart,\n onSpatialDrag,\n onSpatialDragEnd,\n onSpatialRotate,\n onSpatialRotateEnd,\n onSpatialMagnify,\n onSpatialMagnifyEnd,\n ...orbitProps\n } = restProps\n return <SpatializedStatic3DElementContainer ref={ref} {...orbitProps} />\n }\n\n return <SpatializedStatic3DElementContainer ref={ref} {...restProps} />\n}\n\n// No `withSSRSupported` wrapper: on the default entry the real `Model` is\n// reached only through the facade delegate (`facades/Model.tsx`), which renders\n// it only after `useSpatialReady()` reports ready — i.e. as a fresh client\n// mount AFTER hydration commits, never during the SSR or hydration pass. The\n// eager entry exports this real `Model` directly and is CSR-only for spatial\n// primitives (see `spatial-lazy-load` spec \"Entry routing\"); SSR safety in\n// mixed eager setups is the consumer's responsibility (CSR-gate the subtree).\nexport const Model = forwardRef(ModelBase)\nModel.displayName = 'Model'\n// Brand the real implementation too: the eager entry exports THIS `Model`,\n// and the JSX runtime must short-circuit it (not wrap `<Model enable-xr>` as\n// a 2D spatialized container).\nmarkWebSpatialPrimitive(Model, 'Model')\n","import React, { forwardRef } from 'react'\nimport { EntityProps } from '../type'\nimport { EntityRefShape } from '../hooks'\nimport { BaseEntity } from './BaseEntity'\n\ntype Props = EntityProps & { children?: React.ReactNode }\n\nexport const Entity = forwardRef<EntityRefShape, Props>((props, ref) => {\n const { id, name, children, ...rest } = props\n return (\n <BaseEntity\n {...rest}\n id={id}\n ref={ref}\n createEntity={async ctxVal => ctxVal!.session.createEntity({ id, name })}\n >\n {children}\n </BaseEntity>\n )\n})\n","import React, { forwardRef } from 'react'\nimport { SpatialEntity } from '@webspatial/core-sdk'\nimport {\n ParentContext,\n RealityContextValue,\n useRealityContext,\n} from '../context'\nimport { EntityProps, EntityEventHandler } from '../type'\nimport { EntityRefShape, useEntity } from '../hooks'\n\ntype BaseEntityProps = EntityProps &\n EntityEventHandler & {\n children?: React.ReactNode\n recreateKey?: string\n createEntity: (\n ctx: RealityContextValue,\n signal: AbortSignal,\n ) => Promise<SpatialEntity>\n }\n\nexport const BaseEntity = forwardRef<EntityRefShape, BaseEntityProps>(\n ({ children, createEntity, recreateKey, ...rest }, ref) => {\n const ctx = useRealityContext()\n const entity = useEntity({\n ...rest,\n ref,\n recreateKey,\n createEntity: (signal: AbortSignal) => createEntity(ctx, signal),\n })\n\n if (!entity) return null\n return (\n <ParentContext.Provider value={entity}>{children}</ParentContext.Provider>\n )\n },\n)\n","import {\n SpatializedDynamic3DElement,\n SpatialSession,\n} from '@webspatial/core-sdk'\nimport { createContext, useContext } from 'react'\nimport { ResourceRegistry } from '../utils'\nimport { AttachmentRegistry } from './AttachmentContext'\n\nexport type RealityContextValue = {\n session: SpatialSession\n reality: SpatializedDynamic3DElement\n resourceRegistry: ResourceRegistry\n attachmentRegistry: AttachmentRegistry\n} | null\nexport const RealityContext = createContext<RealityContextValue>(null)\nexport const useRealityContext = () => useContext(RealityContext)\n","import { SpatialEntity } from '@webspatial/core-sdk'\nimport { createContext, useContext } from 'react'\n\nexport const ParentContext = createContext<SpatialEntity | null>(null)\nexport const useParentContext = () => useContext(ParentContext)\n","import { createContext, useContext } from 'react'\n\nexport type ContainerEntry = { instanceId: string; container: HTMLElement }\n\ntype ContainersChangeCallback = (containers: ContainerEntry[]) => void\n\nexport class AttachmentRegistry {\n // name → (instanceId → container)\n private containers = new Map<string, Map<string, HTMLElement>>()\n private listeners = new Map<string, ContainersChangeCallback>()\n\n addContainer(name: string, instanceId: string, container: HTMLElement) {\n if (!this.containers.has(name)) {\n this.containers.set(name, new Map())\n }\n this.containers.get(name)!.set(instanceId, container)\n this.notifyListeners(name)\n }\n\n removeContainer(name: string, instanceId: string) {\n this.containers.get(name)?.delete(instanceId)\n if (this.containers.get(name)?.size === 0) {\n this.containers.delete(name)\n }\n this.notifyListeners(name)\n }\n\n getContainers(name: string): ContainerEntry[] {\n const map = this.containers.get(name)\n if (!map) return []\n return Array.from(map, ([instanceId, container]) => ({\n instanceId,\n container,\n }))\n }\n\n onContainersChange(name: string, cb: ContainersChangeCallback): () => void {\n const current = this.getContainers(name)\n if (current.length > 0) {\n cb(current)\n }\n const prev = this.listeners.get(name)\n if (prev) prev([])\n this.listeners.set(name, cb)\n return () => {\n if (this.listeners.get(name) === cb) {\n this.listeners.delete(name)\n }\n }\n }\n\n private notifyListeners(name: string) {\n const cs = this.getContainers(name)\n this.listeners.get(name)?.(cs)\n }\n\n destroy() {\n this.containers.clear()\n this.listeners.clear()\n }\n}\n\nexport const AttachmentContext = createContext<AttachmentRegistry | null>(null)\nexport const useAttachmentContext = () => useContext(AttachmentContext)\n","import { SpatialEntity } from '@webspatial/core-sdk'\nimport type { AnimatedProps, AnimatedPropsInternal } from '@webspatial/core-sdk'\nimport { useEffect, useRef } from 'react'\nimport { EntityProps } from '../type'\nimport { shallowEqualRotation, shallowEqualVec3 } from '../utils'\n\ninterface TransformWithAnimation {\n position?: EntityProps['position']\n rotation?: EntityProps['rotation']\n scale?: EntityProps['scale']\n animation?: AnimatedProps\n}\n\nexport function useEntityTransform(\n entity: SpatialEntity | null,\n { position, rotation, scale, animation }: TransformWithAnimation,\n) {\n const last = useRef<{ position?: any; rotation?: any; scale?: any }>({})\n\n // Read animation.__animating on every render so that when the session ends\n // and a re-render occurs, the value change (true → false) triggers the\n // effect to re-run, allowing us to re-sync the React-declared transform.\n const isAnimating = animation ? animation.__animating : false\n\n useEffect(() => {\n if (!entity) return\n\n // Determine which fields are suppressed by an alive animation session\n const suppressedFields: Set<string> =\n animation && (animation as AnimatedPropsInternal).__getSuppressedFields\n ? new Set(\n (animation as AnimatedPropsInternal).__getSuppressedFields() ?? [],\n )\n : new Set()\n\n // Clear cached values for suppressed fields so that when suppression is\n // released (animation ends) the next effect run will detect a difference\n // between the cached value (now undefined) and the current prop, forcing\n // a re-sync back to the React-declared transform.\n if (suppressedFields.has('position')) last.current.position = undefined\n if (suppressedFields.has('rotation')) last.current.rotation = undefined\n if (suppressedFields.has('scale')) last.current.scale = undefined\n\n // Determine which unsuppressed fields have changed\n const positionChanged =\n !suppressedFields.has('position') &&\n !shallowEqualVec3(last.current.position, position)\n const rotationChanged =\n !suppressedFields.has('rotation') &&\n !shallowEqualRotation(last.current.rotation, rotation)\n const scaleChanged =\n !suppressedFields.has('scale') &&\n !shallowEqualVec3(last.current.scale, scale)\n\n // Cache latest prop values only for non-suppressed fields.\n // Suppressed fields keep their cleared state (undefined) so re-sync\n // is triggered once suppression lifts.\n if (!suppressedFields.has('position')) last.current.position = position\n if (!suppressedFields.has('rotation')) last.current.rotation = rotation\n if (!suppressedFields.has('scale')) last.current.scale = scale\n\n const shouldUpdate = positionChanged || rotationChanged || scaleChanged\n\n if (!shouldUpdate) return\n\n // Build update with only the changed, non-suppressed fields\n const update: Record<string, any> = {}\n if (positionChanged && position) update.position = position\n if (rotationChanged && rotation) update.rotation = rotation\n if (scaleChanged && scale) update.scale = scale\n\n if (Object.keys(update).length === 0) return\n\n const updateTransform = async () => {\n try {\n await entity.updateTransform(update)\n } catch (err) {\n console.error('[useEntityTransform] Failed to update transform:', err)\n }\n }\n\n updateTransform()\n\n return () => {}\n }, [entity, position, rotation, scale, animation, isAnimating])\n}\n","import { SpatialObject } from '@webspatial/core-sdk'\n\n/**\n * Tracks spatial resources (textures, materials, entities, …) by string id under one Reality.\n *\n * Native creation is async (`createTexture`, `createUnlitMaterial`, …). The map\n * stores `Promise<SpatialObject>` so `add(id, pendingCreation)` can run after `get(id)` — sibling\n * JSX order does not need to match registration order. Callers are responsible for using the\n * correct id for each resource kind (same as with string ids today).\n *\n * `get(id)` before `add()` is fine — resolves when `add()` runs.\n * `has(id)` is true only after `add()`, not after `get()` alone.\n *\n * `subscribe` / `notify`: run when a resource settles, is removed, or updates in place (e.g. texture URL).\n */\nexport class ResourceRegistry {\n /** Every id maps to a promise — either the real resource from add(), or a placeholder until then. */\n private resources: Map<string, Promise<SpatialObject>> = new Map()\n /** ids registered via add(), not get()-only waiters */\n private registered = new Set<string>()\n /** If get() ran first, we stash resolve/reject so add() can complete the waiting promise. */\n private deferreds = new Map<\n string,\n {\n resolve: (value: SpatialObject) => void\n reject: (error: Error) => void\n }\n >()\n /** Subscribers are notified whenever an id gets a fresh resolved or failed resource attempt. */\n private listeners = new Map<string, Set<() => void>>()\n\n add<T extends SpatialObject>(id: string, resource: Promise<T>): void {\n this.registered.add(id)\n this.resources.set(id, resource)\n\n // Anyone who awaited get(id) early is still holding the placeholder; wire them to this promise.\n const deferred = this.deferreds.get(id)\n if (deferred) {\n resource\n .then(deferred.resolve)\n .catch(err =>\n deferred.reject(err instanceof Error ? err : new Error(String(err))),\n )\n this.deferreds.delete(id)\n }\n\n // Resource users (e.g. materials bound to a texture id) may need to retry or refresh when\n // a creation attempt settles, even if the id string itself did not change.\n resource.then(() => this.notify(id)).catch(() => this.notify(id))\n }\n\n subscribe(id: string, listener: () => void): () => void {\n const listeners = this.listeners.get(id) ?? new Set<() => void>()\n listeners.add(listener)\n this.listeners.set(id, listeners)\n\n return () => {\n listeners.delete(listener)\n if (listeners.size === 0) {\n this.listeners.delete(id)\n }\n }\n }\n\n notify(id: string): void {\n const listeners = this.listeners.get(id)\n if (!listeners) return\n for (const listener of Array.from(listeners)) {\n listener()\n }\n }\n\n has(id: string): boolean {\n return this.registered.has(id)\n }\n\n get(id: string): Promise<SpatialObject> {\n const existing = this.resources.get(id)\n if (existing) {\n return existing\n }\n\n // Nothing registered yet — return a promise that add() will resolve (or reject on failure).\n const promise = new Promise<SpatialObject>((resolve, reject) => {\n this.deferreds.set(id, { resolve, reject })\n })\n this.resources.set(id, promise)\n return promise\n }\n\n remove(id: string): void {\n this.registered.delete(id)\n this.resources.delete(id)\n this.deferreds.delete(id)\n this.notify(id)\n }\n\n // Same as remove, but when the promise resolves, destroy the spatial object (best-effort).\n removeAndDestroy(id: string): void {\n const p = this.resources.get(id)\n if (p) {\n p.then(obj => obj.destroy()).catch(() => {})\n }\n this.registered.delete(id)\n this.resources.delete(id)\n this.deferreds.delete(id)\n this.notify(id)\n }\n\n destroy(): void {\n // Reality is tearing down: fail any waiter that never saw add().\n for (const [id, deferred] of this.deferreds) {\n deferred.reject(\n new Error(`ResourceRegistry destroyed — \"${id}\" never resolved`),\n )\n }\n this.deferreds.clear()\n\n const ids = Array.from(this.resources.keys())\n for (const id of ids) {\n this.notify(id)\n }\n this.listeners.clear()\n this.registered.clear()\n\n const pending = Array.from(this.resources.values())\n this.resources.clear()\n // Destroy runs when each creation promise settles — may finish after React unmount; still\n // required so native objects are released. Failures/no-ops are swallowed per promise.\n void Promise.allSettled(pending.map(p => p.then(obj => obj.destroy())))\n }\n}\n","export function shallowEqualVec3(\n a?: { x: number; y: number; z: number },\n b?: { x: number; y: number; z: number },\n) {\n if (a === b) return true\n if (!a || !b) return false\n return a.x === b.x && a.y === b.y && a.z === b.z\n}\n\nexport function shallowEqualRotation(a?: any, b?: any) {\n if (a === b) return true\n if (!a || !b) return false\n // support Vec3 / Vec4\n return (\n a.x === b.x && a.y === b.y && a.z === b.z && ('w' in a ? a.w === b.w : true)\n )\n}\n\nexport function shallowEqualObject(\n a?: Record<string, any>,\n b?: Record<string, any>,\n) {\n if (a === b) return true\n if (!a || !b) return false\n const keysA = Object.keys(a)\n const keysB = Object.keys(b)\n if (keysA.length !== keysB.length) return false\n return keysA.every(key => a[key] === b[key])\n}\n\nexport function shallowEqualArray(a?: any[], b?: any[]) {\n if (a === b) return true\n if (!a || !b) return false\n if (a.length !== b.length) return false\n return a.every((val, i) => val === b[i])\n}\n","export class AbortResourceManager {\n private resources: { destroy: () => Promise<void> | void }[] = []\n private aborted = false\n\n constructor(signal: AbortSignal) {\n signal.addEventListener('abort', () => {\n this.aborted = true\n void this.dispose()\n })\n }\n\n async addResource<T extends { destroy: () => Promise<void> | void }>(\n factory: () => Promise<T>,\n ): Promise<T> {\n if (this.aborted) throw new DOMException('Aborted', 'AbortError')\n const resource = await factory()\n if (this.aborted) {\n await resource.destroy()\n throw new DOMException('Aborted', 'AbortError')\n }\n this.resources.push(resource)\n return resource\n }\n\n async dispose() {\n const resources = this.resources.splice(0)\n for (const r of resources) {\n try {\n await r.destroy()\n } catch (e) {\n console.error('AbortResourceManager dispose error:', e, r)\n }\n }\n }\n}\n","import React, { useEffect, useRef } from 'react'\nimport {\n EntityEventHandler,\n eventMap,\n SpatialDragEntityEvent,\n SpatialMagnifyEntityEvent,\n SpatialRotateEntityEvent,\n SpatialDragStartEntityEvent,\n SpatialTapEntityEvent,\n} from '../type'\nimport { EntityRef } from './useEntityRef'\nimport { SpatialEntity } from '@webspatial/core-sdk'\n\nfunction createEventProxy(ev: any, instance: EntityRef) {\n return new Proxy(ev, {\n get(target, prop: PropertyKey) {\n // Align with W3C: currentTarget is the listener owner\n if (prop === 'currentTarget') {\n return instance\n }\n // Align with W3C: target is the original dispatch target\n if (prop === 'target') {\n const origin = (target as any).__origin as SpatialEntity | undefined\n if (origin) {\n // Create a lightweight EntityRef for original target\n return new EntityRef(origin, null)\n }\n // Fallback: if origin not set, return current instance\n return instance\n }\n if (prop === 'bubbles') {\n return true\n }\n if (prop === 'offsetX') {\n const type = (target as any).type\n if (type === 'spatialtap') {\n return (target as SpatialTapEntityEvent).detail?.location3D?.x ?? 0\n }\n if (type === 'spatialdragstart') {\n return (\n (target as SpatialDragStartEntityEvent).detail?.startLocation3D\n ?.x ?? 0\n )\n }\n return undefined\n }\n if (prop === 'offsetY') {\n const type = (target as any).type\n if (type === 'spatialtap') {\n return (target as SpatialTapEntityEvent).detail?.location3D?.y ?? 0\n }\n if (type === 'spatialdragstart') {\n return (\n (target as SpatialDragStartEntityEvent).detail?.startLocation3D\n ?.y ?? 0\n )\n }\n return undefined\n }\n if (prop === 'offsetZ') {\n const type = (target as any).type\n if (type === 'spatialtap') {\n return (target as any).detail?.location3D?.z ?? 0\n }\n if (type === 'spatialdragstart') {\n return (target as any).detail?.startLocation3D?.z ?? 0\n }\n return undefined\n }\n if (prop === 'translationX') {\n const type = (target as any).type\n if (type === 'spatialdrag') {\n return (\n (target as SpatialDragEntityEvent).detail?.translation3D?.x ?? 0\n )\n }\n return undefined\n }\n if (prop === 'translationY') {\n const type = (target as any).type\n if (type === 'spatialdrag') {\n return (\n (target as SpatialDragEntityEvent).detail?.translation3D?.y ?? 0\n )\n }\n return undefined\n }\n if (prop === 'translationZ') {\n const type = (target as any).type\n if (type === 'spatialdrag') {\n return (\n (target as SpatialDragEntityEvent).detail?.translation3D?.z ?? 0\n )\n }\n return undefined\n }\n if (prop === 'quaternion') {\n const type = (target as any).type\n if (type === 'spatialrotate') {\n return (\n (target as SpatialRotateEntityEvent).detail?.quaternion ?? {\n x: 0,\n y: 0,\n z: 0,\n w: 1,\n }\n )\n }\n return undefined\n }\n if (prop === 'magnification') {\n const type = (target as any).type\n if (type === 'spatialmagnify') {\n return (\n (target as SpatialMagnifyEntityEvent).detail?.magnification ?? 1\n )\n }\n return undefined\n }\n if (prop === 'clientX') {\n const type = (target as any).type\n if (type === 'spatialtap' || type === 'spatialdragstart') {\n return (\n (target as SpatialTapEntityEvent).detail?.globalLocation3D?.x ?? 0\n )\n }\n\n return undefined\n }\n if (prop === 'clientY') {\n const type = (target as any).type\n if (type === 'spatialtap' || type === 'spatialdragstart') {\n return (\n (target as SpatialTapEntityEvent).detail?.globalLocation3D?.y ?? 0\n )\n }\n\n return undefined\n }\n if (prop === 'clientZ') {\n const type = (target as any).type\n if (type === 'spatialtap' || type === 'spatialdragstart') {\n return (\n (target as SpatialTapEntityEvent).detail?.globalLocation3D?.z ?? 0\n )\n }\n\n return undefined\n }\n const val = (target as any)[prop]\n return typeof val === 'function' ? val.bind(target) : val\n },\n })\n}\n\ntype Props = {\n instance: EntityRef\n} & EntityEventHandler\nexport const useEntityEvent: React.FC<Props> = ({ instance, ...handlers }) => {\n const eventsSetRef = useRef<Set<string>>(new Set())\n\n useEffect(() => {\n const entity = instance.entity\n if (!entity) return\n\n Object.entries(eventMap).forEach(([reactKey, spatialEvent]) => {\n // add/update handler\n const handlerFn = (handlers as any)[reactKey]\n if (!handlerFn) return\n const wrapped = (ev: any) => handlerFn(createEventProxy(ev, instance))\n entity.addEvent(spatialEvent, wrapped)\n eventsSetRef.current.add(reactKey)\n })\n return () => {}\n }, [instance.entity, ...Object.values(handlers)])\n\n useEffect(() => {\n const entity = instance.entity\n if (!entity) return\n\n return () => {\n // remove all\n for (let x of eventsSetRef.current) {\n entity.removeEvent(x as any)\n }\n eventsSetRef.current.clear()\n }\n }, [instance.entity])\n\n return null\n}\n","import type { Quaternion, Vec3 } from '@webspatial/core-sdk'\nimport type { AnimatedProps } from '@webspatial/core-sdk'\nimport { EntityRefShape } from './hooks'\nimport { SpatialTapEvent as CoreSpatialTapEvent } from '@webspatial/core-sdk'\nimport { SpatialDragStartEvent as CoreSpatialDragStartEvent } from '@webspatial/core-sdk'\nimport { SpatialDragEvent as CoreSpatialDragEvent } from '@webspatial/core-sdk'\nimport { SpatialDragEndEvent as CoreSpatialDragEndEvent } from '@webspatial/core-sdk'\nimport { SpatialRotateEvent as CoreSpatialRotateEvent } from '@webspatial/core-sdk'\nimport { SpatialRotateEndEvent as CoreSpatialRotateEndEvent } from '@webspatial/core-sdk'\nimport { SpatialMagnifyEvent as CoreSpatialMagnifyEvent } from '@webspatial/core-sdk'\nimport { SpatialMagnifyEndEvent as CoreSpatialMagnifyEndEvent } from '@webspatial/core-sdk'\nimport { SpatialEventOptions } from '..'\n\nexport type EntityProps = {\n id?: string\n name?: string\n position?: Vec3\n rotation?: Vec3\n scale?: Vec3\n enableInput?: boolean\n /** Animation prop returned by useEntityAnimation(). */\n animation?: AnimatedProps\n}\n\ntype allTarget<T extends EntityRefShape> = {\n target: T\n currentTarget: T\n}\n// tap\nexport type SpatialTapEntityEvent<T extends EntityRefShape = EntityRefShape> =\n CoreSpatialTapEvent &\n allTarget<T> & {\n readonly offsetX: number\n readonly offsetY: number\n readonly offsetZ: number\n readonly clientX: number\n readonly clientY: number\n readonly clientZ: number\n }\n\n// drag\nexport type SpatialDragStartEntityEvent<\n T extends EntityRefShape = EntityRefShape,\n> = CoreSpatialDragStartEvent &\n allTarget<T> & {\n readonly offsetX: number\n readonly offsetY: number\n readonly offsetZ: number\n readonly clientX: number\n readonly clientY: number\n readonly clientZ: number\n }\n\nexport type SpatialDragEntityEvent<T extends EntityRefShape = EntityRefShape> =\n CoreSpatialDragEvent &\n allTarget<T> & {\n readonly translationX: number\n readonly translationY: number\n readonly translationZ: number\n }\n\nexport type SpatialDragEndEntityEvent<\n T extends EntityRefShape = EntityRefShape,\n> = CoreSpatialDragEndEvent & allTarget<T>\n// rotate\nexport type SpatialRotateEntityEvent<\n T extends EntityRefShape = EntityRefShape,\n> = CoreSpatialRotateEvent &\n allTarget<T> & {\n readonly quaternion: Quaternion\n }\nexport type SpatialRotateEndEntityEvent<\n T extends EntityRefShape = EntityRefShape,\n> = CoreSpatialRotateEndEvent & allTarget<T>\n// magnify\nexport type SpatialMagnifyEntityEvent<\n T extends EntityRefShape = EntityRefShape,\n> = CoreSpatialMagnifyEvent &\n allTarget<T> & {\n readonly magnification: number\n }\nexport type SpatialMagnifyEndEntityEvent<\n T extends EntityRefShape = EntityRefShape,\n> = CoreSpatialMagnifyEndEvent & allTarget<T>\n\nexport type EntityEventHandler = {\n // tap\n onSpatialTap?: (event: SpatialTapEntityEvent) => void\n // drag\n onSpatialDragStart?: (event: SpatialDragStartEntityEvent) => void\n onSpatialDrag?: (event: SpatialDragEntityEvent) => void\n onSpatialDragEnd?: (event: SpatialDragEndEntityEvent) => void\n // rotate\n spatialEventOptions?: SpatialEventOptions\n onSpatialRotate?: (event: SpatialRotateEntityEvent) => void\n onSpatialRotateEnd?: (event: SpatialRotateEndEntityEvent) => void\n // magnify\n onSpatialMagnify?: (event: SpatialMagnifyEntityEvent) => void\n onSpatialMagnifyEnd?: (event: SpatialMagnifyEndEntityEvent) => void\n}\n\nexport const eventMap = {\n // tap\n onSpatialTap: 'spatialtap',\n // drag\n onSpatialDragStart: 'spatialdragstart',\n onSpatialDrag: 'spatialdrag',\n onSpatialDragEnd: 'spatialdragend',\n // rotate\n onSpatialRotate: 'spatialrotate',\n onSpatialRotateEnd: 'spatialrotateend',\n // magnify\n onSpatialMagnify: 'spatialmagnify',\n onSpatialMagnifyEnd: 'spatialmagnifyend',\n} as const\n","import { useImperativeHandle } from 'react'\nimport { Vec3, SpatialEntity } from '@webspatial/core-sdk'\nimport { RealityContextValue } from '../context'\n\nexport interface EntityRefShape {\n convertFromEntityToEntity: (\n fromEntityId: string,\n toEntityId: string,\n position: Vec3,\n ) => Promise<Vec3>\n convertFromEntityToReality: (\n entityId: string,\n position: Vec3,\n ) => Promise<Vec3>\n convertFromRealityToEntity: (\n entityId: string,\n position: Vec3,\n ) => Promise<Vec3>\n id: string | undefined\n name: string | undefined\n entity: SpatialEntity | null\n}\n\nexport const useEntityRef = (\n ref: React.Ref<EntityRefShape>,\n instance: EntityRef,\n) => {\n useImperativeHandle(ref, () => instance)\n}\n\nexport class EntityRef implements EntityRefShape {\n private _entity: SpatialEntity | null\n private _ctx: RealityContextValue | null\n\n constructor(\n entity: SpatialEntity | null = null,\n ctx: RealityContextValue | null = null,\n ) {\n this._entity = entity\n this._ctx = ctx\n }\n\n updateEntity(entity?: SpatialEntity | null) {\n if (entity) this._entity = entity\n }\n\n updateCtx(ctx?: RealityContextValue | null) {\n if (ctx) this._ctx = ctx\n }\n\n destroy() {\n this._entity?.destroy()\n }\n\n get entity() {\n return this._entity\n }\n get id() {\n return this._entity?.userData?.id\n }\n get name() {\n return this._entity?.userData?.name\n }\n\n async convertFromEntityToEntity(\n fromEntityId: string,\n toEntityId: string,\n position: Vec3,\n ): Promise<Vec3> {\n if (!this._entity) return position\n try {\n const fromEnt = await this._ctx?.resourceRegistry.get(fromEntityId)\n const toEnt = await this._ctx?.resourceRegistry.get(toEntityId)\n if (!fromEnt || !toEnt) return position\n const ret = await this._entity.convertFromEntityToEntity(\n fromEnt.id,\n toEnt.id,\n position,\n )\n return ret?.data ?? position\n } catch {\n return position\n }\n }\n\n async convertFromEntityToReality(\n entityId: string,\n position: Vec3,\n ): Promise<Vec3> {\n if (!this._entity) return position\n try {\n const ent = await this._ctx?.resourceRegistry.get(entityId)\n if (!ent) return position\n const ret = await this._entity.convertFromEntityToScene(ent.id, position)\n return ret?.data ?? position\n } catch {\n return position\n }\n }\n\n async convertFromRealityToEntity(\n entityId: string,\n position: Vec3,\n ): Promise<Vec3> {\n if (!this._entity) return position\n try {\n const ent = await this._ctx?.resourceRegistry.get(entityId)\n if (!ent) return position\n const ret = await this._entity.convertFromSceneToEntity(ent.id, position)\n return ret?.data ?? position\n } catch {\n return position\n }\n }\n}\n\nexport function createEntityRefProxy(\n entity: SpatialEntity | null,\n ctx?: RealityContextValue | null,\n): EntityRefShape {\n return new EntityRef(entity, ctx)\n}\n","import { useEffect, useRef } from 'react'\nimport {\n EntityEventHandler,\n eventMap,\n SpatialDragEntityEvent,\n SpatialMagnifyEntityEvent,\n SpatialRotateEntityEvent,\n SpatialDragStartEntityEvent,\n SpatialTapEntityEvent,\n} from '../type'\nimport {\n SpatializedDynamic3DElement,\n SpatialEntity,\n} from '@webspatial/core-sdk'\nimport { EntityRef } from './useEntityRef'\n\nfunction createEventProxy(ev: any, instance: any) {\n return new Proxy(ev, {\n get(target, prop: PropertyKey) {\n // Align with W3C: currentTarget is the listener owner\n if (prop === 'currentTarget') {\n return instance\n }\n // Align with W3C: target is the original dispatch target\n if (prop === 'target') {\n const origin = (target as any).__origin as SpatialEntity | undefined\n if (origin) {\n // Create a lightweight EntityRef for original target\n return new EntityRef(origin, null)\n }\n // Fallback: if origin not set, return current instance\n return instance\n }\n if (prop === 'bubbles') {\n return true\n }\n if (prop === 'offsetX') {\n const type = (target as any).type\n if (type === 'spatialtap') {\n return (target as SpatialTapEntityEvent).detail?.location3D?.x ?? 0\n }\n if (type === 'spatialdragstart') {\n return (\n (target as SpatialDragStartEntityEvent).detail?.startLocation3D\n ?.x ?? 0\n )\n }\n return undefined\n }\n if (prop === 'offsetY') {\n const type = (target as any).type\n if (type === 'spatialtap') {\n return (target as SpatialTapEntityEvent).detail?.location3D?.y ?? 0\n }\n if (type === 'spatialdragstart') {\n return (\n (target as SpatialDragStartEntityEvent).detail?.startLocation3D\n ?.y ?? 0\n )\n }\n return undefined\n }\n if (prop === 'offsetZ') {\n const type = (target as any).type\n if (type === 'spatialtap') {\n return (target as any).detail?.location3D?.z ?? 0\n }\n if (type === 'spatialdragstart') {\n return (target as any).detail?.startLocation3D?.z ?? 0\n }\n return undefined\n }\n if (prop === 'translationX') {\n const type = (target as any).type\n if (type === 'spatialdrag') {\n return (\n (target as SpatialDragEntityEvent).detail?.translation3D?.x ?? 0\n )\n }\n return undefined\n }\n if (prop === 'translationY') {\n const type = (target as any).type\n if (type === 'spatialdrag') {\n return (\n (target as SpatialDragEntityEvent).detail?.translation3D?.y ?? 0\n )\n }\n return undefined\n }\n if (prop === 'translationZ') {\n const type = (target as any).type\n if (type === 'spatialdrag') {\n return (\n (target as SpatialDragEntityEvent).detail?.translation3D?.z ?? 0\n )\n }\n return undefined\n }\n if (prop === 'quaternion') {\n const type = (target as any).type\n if (type === 'spatialrotate') {\n return (\n (target as SpatialRotateEntityEvent).detail?.quaternion ?? {\n x: 0,\n y: 0,\n z: 0,\n w: 1,\n }\n )\n }\n return undefined\n }\n if (prop === 'magnification') {\n const type = (target as any).type\n if (type === 'spatialmagnify') {\n return (\n (target as SpatialMagnifyEntityEvent).detail?.magnification ?? 1\n )\n }\n return undefined\n }\n if (prop === 'clientX') {\n const type = (target as any).type\n if (type === 'spatialtap' || type === 'spatialdragstart') {\n return (\n (target as SpatialTapEntityEvent).detail?.globalLocation3D?.x ?? 0\n )\n }\n\n return undefined\n }\n if (prop === 'clientY') {\n const type = (target as any).type\n if (type === 'spatialtap' || type === 'spatialdragstart') {\n return (\n (target as SpatialTapEntityEvent).detail?.globalLocation3D?.y ?? 0\n )\n }\n\n return undefined\n }\n if (prop === 'clientZ') {\n const type = (target as any).type\n if (type === 'spatialtap' || type === 'spatialdragstart') {\n return (\n (target as SpatialTapEntityEvent).detail?.globalLocation3D?.z ?? 0\n )\n }\n\n return undefined\n }\n const val = (target as any)[prop]\n return typeof val === 'function' ? val.bind(target) : val\n },\n })\n}\n\ntype Props = {\n instance: SpatializedDynamic3DElement | null\n} & EntityEventHandler\n\n/**\n * useRealityEvents is a hook that manages spatial events for a SpatializedDynamic3DElement.\n * Handlers receive CustomEvents with proxy to support common event properties.\n */\nexport const useRealityEvents = ({ instance, ...handlers }: Props) => {\n const eventsSetRef = useRef<Set<string>>(new Set())\n\n useEffect(() => {\n if (!instance) return\n\n Object.entries(eventMap).forEach(([reactKey, spatialEvent]) => {\n const handlerFn = (handlers as any)[reactKey]\n if (!handlerFn) return\n\n const wrapped = (ev: any) => handlerFn(createEventProxy(ev, instance))\n instance.addEvent(spatialEvent as any, wrapped)\n eventsSetRef.current.add(spatialEvent)\n })\n\n return () => {\n if (instance) {\n for (let x of eventsSetRef.current) {\n instance.removeEvent(x as any)\n }\n eventsSetRef.current.clear()\n }\n }\n }, [instance, ...Object.values(handlers)])\n}\n","import { SpatialEntity } from '@webspatial/core-sdk'\nimport React, { useEffect } from 'react'\nimport { useRealityContext } from '../context'\ntype Props = {\n id?: string\n entity?: SpatialEntity | null\n}\nexport const useEntityId: React.FC<Props> = ({ id, entity }) => {\n const ctx = useRealityContext()\n useEffect(() => {\n if (!id || !entity || !ctx) return\n ctx.resourceRegistry.add(id, Promise.resolve(entity))\n return () => {\n ctx.resourceRegistry.remove(id)\n }\n }, [id, entity, ctx])\n\n return null\n}\n","import { ForwardedRef, useEffect, useRef } from 'react'\nimport { SpatialEntity } from '@webspatial/core-sdk'\nimport type { AnimatedProps, AnimatedPropsInternal } from '@webspatial/core-sdk'\nimport { useRealityContext, useParentContext } from '../context'\nimport { EntityEventHandler, EntityProps } from '../type'\nimport {\n EntityRefShape,\n EntityRef,\n useEntityEvent,\n useEntityId,\n useEntityRef,\n useEntityTransform,\n useForceUpdate,\n} from '../hooks'\n\ntype UseEntityOptions = {\n createEntity: (signal: AbortSignal) => Promise<SpatialEntity>\n recreateKey?: string\n} & EntityProps &\n EntityEventHandler & { ref: ForwardedRef<EntityRefShape> }\n\nexport const useEntity = ({\n ref,\n id,\n position,\n rotation,\n scale,\n enableInput,\n animation,\n onSpatialTap,\n onSpatialDragStart,\n onSpatialDrag,\n onSpatialDragEnd,\n onSpatialRotate,\n onSpatialRotateEnd,\n onSpatialMagnify,\n onSpatialMagnifyEnd,\n createEntity,\n recreateKey,\n}: UseEntityOptions) => {\n const ctx = useRealityContext()\n const parent = useParentContext()\n const instanceRef = useRef<EntityRef>(new EntityRef(null, ctx))\n\n const forceUpdate = useForceUpdate()\n\n // Track the current animation prop for bind/unbind\n const prevAnimationRef = useRef<AnimatedProps | undefined>(undefined)\n\n useEffect(() => {\n if (!ctx) return\n\n const controller = new AbortController()\n\n const init = async () => {\n try {\n const ent = await createEntity(controller.signal)\n if (!ent) return\n if (controller.signal.aborted) {\n ent.destroy()\n return\n }\n // Apply transform before adding to scene so it never flashes at default scale\n await ent.updateTransform({ position, rotation, scale })\n if (controller.signal.aborted) {\n ent.destroy()\n return\n }\n if (parent) {\n const result = await parent.addEntity(ent)\n if (!result.success) throw new Error('parent.addEntity failed')\n } else {\n const result = await ctx.reality.addEntity(ent)\n if (!result.success) throw new Error('ctx.reality.addEntity failed')\n }\n\n instanceRef.current?.updateEntity(ent)\n\n // Bind animation if present\n if (animation) {\n ;(animation as AnimatedPropsInternal).__bind?.(ent)\n prevAnimationRef.current = animation\n }\n\n forceUpdate()\n } catch (error) {\n console.error('useEntity init ~ error:', error)\n }\n }\n\n init()\n\n return () => {\n controller.abort()\n // Unbind animation on cleanup\n if (prevAnimationRef.current) {\n ;(prevAnimationRef.current as AnimatedPropsInternal).__unbind?.()\n prevAnimationRef.current = undefined\n }\n instanceRef.current?.destroy()\n }\n }, [ctx, parent, recreateKey])\n\n // Handle animation prop changes after initial mount\n useEffect(() => {\n const entity = instanceRef.current.entity\n if (!entity) return\n\n const prevAnimation = prevAnimationRef.current\n\n if (prevAnimation === animation) return\n\n // Unbind old animation\n if (prevAnimation) {\n ;(prevAnimation as AnimatedPropsInternal).__unbind?.()\n }\n\n // Bind new animation\n if (animation) {\n ;(animation as AnimatedPropsInternal).__bind?.(entity)\n }\n\n prevAnimationRef.current = animation\n }, [animation, instanceRef.current.entity])\n\n useEntityId({ id, entity: instanceRef.current.entity })\n useEntityTransform(instanceRef.current.entity, {\n position,\n rotation,\n scale,\n animation,\n })\n useEntityRef(ref, instanceRef.current)\n\n useEntityEvent({\n instance: instanceRef.current,\n onSpatialTap,\n onSpatialDragStart,\n onSpatialDrag,\n onSpatialDragEnd,\n onSpatialRotate,\n onSpatialRotateEnd,\n onSpatialMagnify,\n onSpatialMagnifyEnd,\n })\n\n useEffect(() => {\n const ent = instanceRef.current.entity\n if (!ent) return\n if (enableInput !== undefined) {\n ent.enableInput = !!enableInput\n }\n }, [instanceRef.current.entity, enableInput])\n\n return instanceRef.current.entity\n}\n","import { useCallback, useState } from 'react'\nexport const useForceUpdate = () => {\n const [, setTick] = useState(0)\n return useCallback(() => setTick(tick => tick + 1), [])\n}\n","import { useCallback, useEffect, useMemo, useRef, useReducer } from 'react'\nimport { SpatialEntity, composeSRT } from '@webspatial/core-sdk'\nimport type {\n AnimatedPropsInternal,\n AnimationConfig,\n AnimationPlayState,\n AnimationApi,\n AnimatedProps,\n AnimateTransformCommand,\n AnimateTransformResult,\n AnimationError,\n TransformValues,\n Vec3,\n} from '@webspatial/core-sdk'\nimport {\n validateAnimationConfig,\n getAnimatedFields,\n} from './animationValidator'\n\n// ---- Internal types ----\n\ntype SessionState =\n | 'idle'\n | 'queued'\n | 'delaying'\n | 'running'\n | 'paused'\n | 'finished'\n\ninterface AnimationSession {\n animationId: string\n state: SessionState\n /** Transform fields controlled by this session. */\n fields: readonly ('position' | 'rotation' | 'scale')[]\n /** The config snapshot used for this session. */\n config: AnimationConfig\n /** Result from core animateTransform (play). */\n result?: AnimateTransformResult\n /** Whether a queued pause was requested before bind. */\n queuedPause?: boolean\n /** Whether unmounted — suppress callbacks after unmount. */\n unmounted?: boolean\n}\n\nlet _animObjectCounter = 0\nfunction nextAnimObjectId(): string {\n return `__anim_${++_animObjectCounter}_${Date.now()}`\n}\n\nlet _sessionCounter = 0\nfunction nextAnimationId(): string {\n return `anim_${++_sessionCounter}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`\n}\n\n// ---- Track bound animation objects per entity ----\nconst _boundAnimations = new WeakMap<object, string>()\n\n/**\n * Internal entity animation hook.\n * Called unconditionally by the dispatch layer; `active` controls whether effects run.\n * When `active` is false, all hooks still execute but effects short-circuit.\n */\nexport function useEntityAnimation(\n config: AnimationConfig,\n active: boolean = true,\n): [AnimatedProps, AnimationApi] {\n // Validate config eagerly (throws on invalid) — only when active\n if (active) {\n validateAnimationConfig(config)\n }\n\n const animatedFields = useMemo(\n () => getAnimatedFields(config),\n [\n config.to.position !== undefined,\n config.to.rotation !== undefined,\n config.to.scale !== undefined,\n ],\n )\n\n // Stable animation object ID for the lifetime of this hook instance\n const animObjectId = useRef(nextAnimObjectId()).current\n\n // Mutable refs\n const configRef = useRef<AnimationConfig>(config)\n configRef.current = config\n\n const sessionRef = useRef<AnimationSession | null>(null)\n const entityRef = useRef<SpatialEntity | null>(null)\n const unmountedRef = useRef(false)\n const finishedRef = useRef(false)\n\n // Trigger a re-render when a session ends so that useEntityTransform\n // re-runs and syncs the React-declared transform back to native.\n const [, bumpSyncVersion] = useReducer((x: number) => x + 1, 0)\n\n // ---- Command queue for serializing bridge calls ----\n const commandQueueRef = useRef<Promise<void>>(Promise.resolve())\n\n const enqueueCommand = useCallback((fn: () => Promise<void>) => {\n commandQueueRef.current = commandQueueRef.current.then(fn, fn)\n }, [])\n\n // ---- Helper: fire onError or console.error ----\n const reportError = useCallback((error: AnimationError) => {\n if (unmountedRef.current) return\n const cfg = configRef.current\n if (cfg.onError) {\n cfg.onError(error)\n } else {\n console.error('[useEntityAnimation] Animation error:', error)\n }\n }, [])\n\n // ---- Helper: convert TransformValues to Float4x4 ----\n const toMatrix = useCallback(\n (values: TransformValues, entity: SpatialEntity): Float64Array => {\n const pos: Vec3 = values.position ?? entity.position\n const rot: Vec3 = values.rotation ?? entity.rotation\n const scl: Vec3 = values.scale ?? entity.scale\n return composeSRT(pos, rot, scl).toFloat64Array()\n },\n [],\n )\n\n // ---- Core: send play to native ----\n const doPlay = useCallback(\n async (session: AnimationSession, entity: SpatialEntity) => {\n const cfg = session.config\n\n // Build the command\n const cmd: AnimateTransformCommand = {\n animationId: session.animationId,\n type: 'play',\n entityId: entity.id,\n duration: cfg.duration ?? 0.3,\n timingFunction: cfg.timingFunction ?? 'easeInOut',\n delay: cfg.delay ?? 0,\n loop: cfg.loop,\n playbackRate: cfg.playbackRate,\n }\n\n // Build toTransform from the fields in to\n const toValues: TransformValues = {}\n if (cfg.to.position) toValues.position = cfg.to.position\n if (cfg.to.rotation) toValues.rotation = cfg.to.rotation\n if (cfg.to.scale) toValues.scale = cfg.to.scale\n cmd.toTransform = toMatrix(toValues, entity)\n\n // Build fromTransform if from is specified\n if (cfg.from) {\n const fromValues: TransformValues = {}\n if (cfg.from.position) fromValues.position = cfg.from.position\n if (cfg.from.rotation) fromValues.rotation = cfg.from.rotation\n if (cfg.from.scale) fromValues.scale = cfg.from.scale\n cmd.fromTransform = toMatrix(fromValues, entity)\n }\n\n try {\n const result = await entity.animateTransform(\n cmd as AnimateTransformCommand & { type: 'play' },\n )\n session.result = result\n\n // If session was stopped or replaced while waiting for bridge ack, skip\n if (sessionRef.current !== session || session.unmounted) return\n\n // Transition state\n if (session.queuedPause) {\n session.state = 'paused'\n } else if ((cfg.delay ?? 0) > 0) {\n session.state = 'delaying'\n } else {\n session.state = 'running'\n }\n\n // Fire onStart\n if (!session.unmounted && cfg.onStart) {\n cfg.onStart()\n }\n\n // Listen for terminal events\n result.finished.then((values: TransformValues) => {\n if (sessionRef.current !== session || session.unmounted) return\n session.state = 'finished'\n finishedRef.current = true\n sessionRef.current = null\n if (!session.unmounted && cfg.onComplete) {\n cfg.onComplete(values)\n }\n bumpSyncVersion()\n })\n\n result.canceled.then((values: TransformValues) => {\n if (session.unmounted) return\n // sessionRef may already be null if doCancel's enqueueCommand resolved\n // before this event arrived — that's fine, proceed with cleanup.\n if (sessionRef.current === session) {\n session.state = 'idle'\n sessionRef.current = null\n }\n finishedRef.current = false\n if (cfg.onCancel) {\n cfg.onCancel(values)\n }\n bumpSyncVersion()\n })\n\n // Listen for failed event\n if (result.failed) {\n result.failed.then((error: AnimationError) => {\n if (sessionRef.current !== session || session.unmounted) return\n session.state = 'idle'\n sessionRef.current = null\n reportError(error)\n })\n }\n } catch (err: any) {\n if (sessionRef.current !== session || session.unmounted) return\n session.state = 'idle'\n sessionRef.current = null\n reportError({\n animationId: session.animationId,\n command: 'play',\n reason: err?.message ?? String(err),\n })\n }\n },\n [toMatrix, reportError],\n )\n\n // ---- Core: cancel session ----\n const doCancel = useCallback(\n async (session: AnimationSession, entity: SpatialEntity) => {\n if (session.state === 'queued') {\n // Not yet sent to native, just cancel locally\n session.state = 'idle'\n return\n }\n\n try {\n await entity.animateTransform({\n animationId: session.animationId,\n type: 'cancel',\n })\n } catch (err: any) {\n reportError({\n animationId: session.animationId,\n command: 'cancel',\n reason: err?.message ?? String(err),\n })\n throw err // propagate to block start-new\n }\n },\n [reportError],\n )\n\n // ---- AnimationApi methods ----\n\n const play = useCallback(() => {\n const currentSession = sessionRef.current\n const entity = entityRef.current\n\n // Already playing or queued — calling play() again is a no-op (Web Animation API semantics).\n if (\n currentSession &&\n (currentSession.state === 'running' ||\n currentSession.state === 'delaying' ||\n currentSession.state === 'queued')\n ) {\n return\n }\n\n // If paused, resume the same session instead of creating a new one\n if (currentSession && currentSession.state === 'paused') {\n if (currentSession.queuedPause) {\n // Was paused while queued — undo the queued pause\n currentSession.queuedPause = false\n currentSession.state = 'queued'\n return\n }\n\n enqueueCommand(async () => {\n if (\n !entity ||\n currentSession !== sessionRef.current ||\n currentSession.unmounted\n )\n return\n if (currentSession.state !== 'paused') return\n\n try {\n await entity.animateTransform({\n animationId: currentSession.animationId,\n type: 'resume',\n })\n currentSession.state = 'running'\n bumpSyncVersion()\n } catch (err: any) {\n reportError({\n animationId: currentSession.animationId,\n command: 'resume',\n reason: err?.message ?? String(err),\n })\n }\n })\n return\n }\n\n // Start a new session\n const cfg = configRef.current\n const prevSession = currentSession\n\n const newSession: AnimationSession = {\n animationId: nextAnimationId(),\n state: entity ? 'running' : 'queued',\n fields: getAnimatedFields(cfg),\n config: { ...cfg },\n }\n\n // Reset finished flag on new play\n finishedRef.current = false\n\n enqueueCommand(async () => {\n if (unmountedRef.current) return\n\n // Cancel previous session first\n if (\n prevSession &&\n prevSession.state !== 'idle' &&\n prevSession.state !== 'finished'\n ) {\n try {\n if (entity) {\n await doCancel(prevSession, entity)\n }\n prevSession.state = 'idle'\n if (!prevSession.unmounted && prevSession.config.onCancel) {\n prevSession.config.onCancel({\n position: entity?.position,\n rotation: entity?.rotation,\n scale: entity?.scale,\n })\n }\n } catch {\n // cancel-old failure blocks start-new\n return\n }\n }\n\n sessionRef.current = newSession\n bumpSyncVersion()\n\n if (entity) {\n await doPlay(newSession, entity)\n }\n // else: stays queued, will play on bind\n })\n }, [enqueueCommand, doCancel, doPlay, reportError])\n\n const pause = useCallback(() => {\n const session = sessionRef.current\n if (!session) return\n if (session.state === 'idle') return\n const entity = entityRef.current\n\n if (session.state === 'queued') {\n session.queuedPause = true\n session.state = 'paused'\n bumpSyncVersion()\n return\n }\n\n enqueueCommand(async () => {\n if (!entity || session !== sessionRef.current || session.unmounted) return\n if (session.state !== 'delaying' && session.state !== 'running') return\n\n try {\n await entity.animateTransform({\n animationId: session.animationId,\n type: 'pause',\n })\n session.state = 'paused'\n bumpSyncVersion()\n } catch (err: any) {\n reportError({\n animationId: session.animationId,\n command: 'pause',\n reason: err?.message ?? String(err),\n })\n }\n })\n }, [enqueueCommand, reportError])\n\n const cancel = useCallback(() => {\n const session = sessionRef.current\n if (!session) return\n if (session.state === 'idle' || session.state === 'finished') return\n const entity = entityRef.current\n\n if (session.state === 'queued') {\n session.state = 'idle'\n sessionRef.current = null\n if (session.config.onCancel) {\n session.config.onCancel({\n position: entity?.position,\n rotation: entity?.rotation,\n scale: entity?.scale,\n })\n }\n bumpSyncVersion()\n return\n }\n\n enqueueCommand(async () => {\n if (!entity || session !== sessionRef.current || session.unmounted) return\n if (session.state === 'idle' || session.state === 'finished') return\n\n try {\n await doCancel(session, entity)\n session.state = 'idle'\n sessionRef.current = null\n\n // Eagerly restore entity to the from-transform on the JS side.\n // This guarantees visual restoration even if the native cancel event\n // is delayed or the native layer does not restore the transform.\n const cfg = session.config\n const restoreValues: TransformValues = {}\n if (cfg.from) {\n if (cfg.from.position) restoreValues.position = cfg.from.position\n if (cfg.from.rotation) restoreValues.rotation = cfg.from.rotation\n if (cfg.from.scale) restoreValues.scale = cfg.from.scale\n }\n if (Object.keys(restoreValues).length > 0) {\n await entity.updateTransform(restoreValues)\n }\n\n // onCancel will also be triggered by the canceled promise in doPlay\n } catch {\n // error already reported in doCancel\n }\n })\n }, [enqueueCommand, doCancel])\n\n // ---- Build AnimationApi ----\n const api: AnimationApi = useMemo(\n () => ({\n play,\n pause,\n cancel,\n get isAnimating() {\n const s = sessionRef.current\n if (!s) return false\n return (\n s.state === 'queued' ||\n s.state === 'delaying' ||\n s.state === 'running'\n )\n },\n get isPaused() {\n const s = sessionRef.current\n if (!s) return false\n return s.state === 'paused'\n },\n get playState(): AnimationPlayState {\n const s = sessionRef.current\n if (!s) return finishedRef.current ? 'finished' : 'idle'\n switch (s.state) {\n case 'queued':\n return 'queued'\n case 'delaying':\n case 'running':\n return 'running'\n case 'paused':\n return 'paused'\n case 'finished':\n return 'finished'\n case 'idle':\n default:\n return 'idle'\n }\n },\n get finished() {\n return finishedRef.current\n },\n }),\n [play, pause, cancel],\n )\n\n // ---- Build AnimatedProps ----\n const animatedProps: AnimatedProps = useMemo(\n () => ({\n __animationObjectId: animObjectId,\n __animatedFields: animatedFields,\n get __animating() {\n const s = sessionRef.current\n return s !== null && s.state !== 'idle'\n },\n }),\n [animObjectId, animatedFields],\n )\n\n // ---- Bind / unbind lifecycle (called by useEntity) ----\n // Store bind/unbind functions on the animatedProps object for the entity layer to call.\n ;(animatedProps as AnimatedPropsInternal).__bind = (\n entity: SpatialEntity,\n ) => {\n entityRef.current = entity\n\n // Check for multi-entity binding\n const existingId = _boundAnimations.get(animatedProps)\n if (existingId && existingId !== entity.id) {\n throw new Error(\n '[useEntityAnimation] The same animation object must not be bound to multiple entities.',\n )\n }\n _boundAnimations.set(animatedProps, entity.id)\n\n // If there's a queued session, execute it now\n const session = sessionRef.current\n if (session && session.state === 'queued') {\n enqueueCommand(async () => {\n if (session !== sessionRef.current || session.unmounted) return\n await doPlay(session, entity)\n })\n }\n }\n ;(animatedProps as AnimatedPropsInternal).__unbind = () => {\n const entity = entityRef.current\n const session = sessionRef.current\n\n if (session && entity) {\n session.unmounted = true\n if (session.state !== 'idle' && session.state !== 'queued') {\n // Fire and forget stop to native\n entity\n .animateTransform({\n animationId: session.animationId,\n type: 'cancel',\n })\n .catch(() => {})\n entity.cleanupAnimationListeners(session.animationId)\n }\n sessionRef.current = null\n }\n\n _boundAnimations.delete(animatedProps)\n entityRef.current = null\n }\n\n // Expose a getter for the entity layer to read suppressed fields\n ;(animatedProps as AnimatedPropsInternal).__getSuppressedFields = ():\n | readonly ('position' | 'rotation' | 'scale')[]\n | null => {\n const session = sessionRef.current\n if (!session || session.state === 'idle') return null\n return session.fields\n }\n\n // ---- Cleanup on unmount ----\n useEffect(() => {\n if (!active) return\n unmountedRef.current = false\n return () => {\n unmountedRef.current = true\n const session = sessionRef.current\n if (session) {\n session.unmounted = true\n }\n }\n }, [active])\n\n // ---- Auto-start logic ----\n useEffect(() => {\n if (!active) return\n const autoStart = config.autoStart !== false\n if (autoStart && !sessionRef.current) {\n play()\n }\n }, [active]) // only on mount\n\n return [animatedProps, api]\n}\n","import type { AnimationConfig, Vec3 } from '@webspatial/core-sdk'\n\n// Defined locally to avoid pulling runtime-dependent code via noRuntime alias\nconst VALID_TIMING_FUNCTIONS = [\n 'linear',\n 'easeIn',\n 'easeOut',\n 'easeInOut',\n] as const\n/**\n * Validate an AnimationConfig at call time.\n * Throws on programmer errors so they surface immediately.\n */\nexport function validateAnimationConfig(config: AnimationConfig): void {\n // to is required and must have at least one transform field\n if (!config.to) {\n throw new Error('[useAnimation] config.to is required')\n }\n const hasTo =\n config.to.position !== undefined ||\n config.to.rotation !== undefined ||\n config.to.scale !== undefined\n if (!hasTo) {\n throw new Error(\n '[useAnimation] config.to must specify at least one of position, rotation, or scale',\n )\n }\n\n // duration\n if (config.duration !== undefined) {\n if (\n typeof config.duration !== 'number' ||\n !isFinite(config.duration) ||\n config.duration <= 0\n ) {\n throw new Error(\n '[useAnimation] config.duration must be a positive finite number',\n )\n }\n }\n\n // delay\n if (config.delay !== undefined) {\n if (\n typeof config.delay !== 'number' ||\n !isFinite(config.delay) ||\n config.delay < 0\n ) {\n throw new Error(\n '[useAnimation] config.delay must be a non-negative finite number',\n )\n }\n }\n\n // timingFunction\n if (config.timingFunction !== undefined) {\n if (\n !(VALID_TIMING_FUNCTIONS as readonly string[]).includes(\n config.timingFunction,\n )\n ) {\n throw new Error(\n `[useAnimation] config.timingFunction must be one of: ${VALID_TIMING_FUNCTIONS.join(', ')}`,\n )\n }\n }\n\n // loop\n if (config.loop !== undefined && config.loop !== false) {\n if (config.loop === true) {\n // ok\n } else if (typeof config.loop === 'object' && config.loop !== null) {\n const keys = Object.keys(config.loop)\n for (const k of keys) {\n if (k !== 'reverse') {\n throw new Error(\n `[useAnimation] config.loop object contains unknown key \"${k}\"`,\n )\n }\n }\n if (\n (config.loop as { reverse?: boolean }).reverse !== undefined &&\n typeof (config.loop as { reverse?: boolean }).reverse !== 'boolean'\n ) {\n throw new Error('[useAnimation] config.loop.reverse must be a boolean')\n }\n } else {\n throw new Error(\n '[useAnimation] config.loop must be true, false, undefined, or { reverse?: boolean }',\n )\n }\n }\n\n // playbackRate\n if (config.playbackRate !== undefined) {\n if (\n typeof config.playbackRate !== 'number' ||\n !isFinite(config.playbackRate) ||\n config.playbackRate <= 0\n ) {\n throw new Error(\n '[useAnimation] config.playbackRate must be a positive finite number (> 0)',\n )\n }\n }\n\n // Validate transform values\n if (config.to.position) validateVec3(config.to.position, 'to.position')\n if (config.to.rotation) validateVec3(config.to.rotation, 'to.rotation')\n if (config.to.scale) validateScaleVec3(config.to.scale, 'to.scale')\n\n if (config.from) {\n if (config.from.position)\n validateVec3(config.from.position, 'from.position')\n if (config.from.rotation)\n validateVec3(config.from.rotation, 'from.rotation')\n if (config.from.scale) validateScaleVec3(config.from.scale, 'from.scale')\n }\n}\n\nfunction validateVec3(v: Vec3, label: string): void {\n if (!isFinite(v.x) || !isFinite(v.y) || !isFinite(v.z)) {\n throw new Error(\n `[useAnimation] config.${label} components must be finite numbers`,\n )\n }\n}\n\nfunction validateScaleVec3(v: Vec3, label: string): void {\n validateVec3(v, label)\n if (v.x < 0 || v.y < 0 || v.z < 0) {\n throw new Error(\n `[useAnimation] config.${label} components must be non-negative`,\n )\n }\n}\n\n/**\n * Extract which transform fields are targeted by the animation config.\n */\nexport function getAnimatedFields(\n config: AnimationConfig,\n): ('position' | 'rotation' | 'scale')[] {\n const fields: ('position' | 'rotation' | 'scale')[] = []\n if (config.to.position !== undefined) fields.push('position')\n if (config.to.rotation !== undefined) fields.push('rotation')\n if (config.to.scale !== undefined) fields.push('scale')\n return fields\n}\n","import React, { forwardRef } from 'react'\nimport { EntityProps } from '../type'\nimport { EntityRefShape } from '../hooks'\nimport { SpatialBoxGeometryOptions } from '@webspatial/core-sdk'\nimport { GeometryEntity } from './GeometryEntity'\nimport { useRealityContext } from '../context'\n\ntype BoxEntityProps = EntityProps & {\n children?: React.ReactNode\n materials?: string[]\n} & SpatialBoxGeometryOptions\n\nexport const BoxEntity = forwardRef<EntityRefShape, BoxEntityProps>(\n ({ children, ...props }, ref) => {\n const ctx = useRealityContext()\n return (\n <GeometryEntity\n {...props}\n ref={ref}\n createGeometry={options => ctx!.session.createBoxGeometry(options)}\n geometryOptions={{\n width: props.width,\n height: props.height,\n depth: props.depth,\n cornerRadius: props.cornerRadius,\n splitFaces: props.splitFaces,\n }}\n >\n {children}\n </GeometryEntity>\n )\n },\n)\n","import React, { forwardRef, useEffect, useRef } from 'react'\nimport { EntityProps, EntityEventHandler } from '../type'\nimport { EntityRefShape } from '../hooks'\nimport {\n SpatialMaterial,\n SpatialGeometry,\n SpatialComponent,\n SpatialEntity,\n} from '@webspatial/core-sdk'\nimport { AbortResourceManager } from '../utils'\nimport { shallowEqualObject, shallowEqualArray } from '../utils'\nimport { BaseEntity } from './BaseEntity'\nimport { useRealityContext } from '../context'\n\ntype GeometryEntityProps = EntityProps &\n EntityEventHandler & {\n children?: React.ReactNode\n materials?: string[]\n geometryOptions: any\n createGeometry: (options: any) => Promise<SpatialGeometry>\n }\n\ntype LastGeometrySnapshot = {\n geometryOptions: any\n materials: string[] | undefined\n}\n\ntype GeometryEntityMutable = {\n lastSnapshot: LastGeometrySnapshot | null\n rebuildGen: number\n}\n\nexport const GeometryEntity = forwardRef<EntityRefShape, GeometryEntityProps>(\n (\n { id, children, name, materials, geometryOptions, createGeometry, ...rest },\n ref,\n ) => {\n const ctx = useRealityContext()\n const entityRef = useRef<SpatialEntity | null>(null)\n const componentRef = useRef<SpatialComponent | null>(null)\n // Tracks the last applied mesh + materials, plus a generation counter so\n // overlapping async rebuilds (e.g. fast sliders) cannot apply out of order.\n const mutableRef = useRef<GeometryEntityMutable>({\n lastSnapshot: null,\n rebuildGen: 0,\n })\n\n useEffect(() => {\n const { lastSnapshot } = mutableRef.current\n if (!ctx || !entityRef.current || lastSnapshot === null) return\n\n // Parents may pass a new options object each render with the same values;\n // shallow compare avoids ripping down the mesh when nothing meaningful changed.\n const geometryChanged = !shallowEqualObject(\n lastSnapshot.geometryOptions,\n geometryOptions,\n )\n const materialsChanged = !shallowEqualArray(\n lastSnapshot.materials,\n materials,\n )\n\n if (!geometryChanged && !materialsChanged) return\n\n mutableRef.current.lastSnapshot = { geometryOptions, materials }\n mutableRef.current.rebuildGen += 1\n const gen = mutableRef.current.rebuildGen\n\n const rebuild = async () => {\n const entity = entityRef.current\n if (!entity) return\n\n try {\n const oldComponent = componentRef.current\n if (oldComponent) {\n // TODO(P2): Rebuild removes/destroys the model component but not the previous mesh\n // `SpatialGeometry`; those objects stay registered until explicitly destroyed (native\n // `SpatialModelComponent.onDestroy` also only nils `mesh`). Destroy the prior mesh after\n // teardown or fix cascade destroy on the Swift side to cap memory on long-lived updates.\n await entity.removeComponent(oldComponent)\n await oldComponent.destroy()\n componentRef.current = null\n if (gen !== mutableRef.current.rebuildGen) return\n }\n\n const geometry = await createGeometry(geometryOptions)\n // A newer rebuild started; drop this mesh so it is not left orphaned.\n if (gen !== mutableRef.current.rebuildGen) {\n await geometry.destroy()\n return\n }\n\n const materialList = (await Promise.all(\n materials\n ?.map(mid => ctx.resourceRegistry.get(mid))\n .filter(Boolean) ?? [],\n )) as SpatialMaterial[]\n if (gen !== mutableRef.current.rebuildGen) {\n await geometry.destroy()\n return\n }\n\n const modelComponent = await ctx.session.createModelComponent({\n mesh: geometry,\n materials: materialList,\n })\n if (gen !== mutableRef.current.rebuildGen) {\n await modelComponent.destroy()\n await geometry.destroy()\n return\n }\n\n await entity.addComponent(modelComponent)\n componentRef.current = modelComponent\n } catch (error) {\n if (gen === mutableRef.current.rebuildGen) {\n console.error('GeometryEntity: rebuild failed', error)\n }\n }\n }\n rebuild()\n }, [ctx, geometryOptions, materials, createGeometry])\n\n return (\n <BaseEntity\n {...rest}\n id={id}\n ref={ref}\n createEntity={async (ctx, signal) => {\n const manager = new AbortResourceManager(signal)\n try {\n const ent = await manager.addResource(() =>\n ctx!.session.createEntity({ id, name }),\n )\n\n const geometry = await manager.addResource(() =>\n createGeometry(geometryOptions),\n )\n\n const materialList = (await Promise.all(\n materials\n ?.map(id => ctx!.resourceRegistry.get(id))\n .filter(Boolean) ?? [],\n )) as SpatialMaterial[]\n const modelComponent = await manager.addResource(() =>\n ctx!.session.createModelComponent({\n mesh: geometry,\n materials: materialList,\n }),\n )\n\n await ent.addComponent(modelComponent)\n\n entityRef.current = ent\n componentRef.current = modelComponent\n mutableRef.current.lastSnapshot = { geometryOptions, materials }\n\n return ent\n } catch (error) {\n await manager.dispose()\n return null as any\n }\n }}\n >\n {children}\n </BaseEntity>\n )\n },\n)\n","import React, { useEffect, useRef, useState } from 'react'\nimport {\n SpatialUnlitMaterial,\n SpatialUnlitMaterialOptions,\n} from '@webspatial/core-sdk'\nimport { useRealityContext } from '../context'\n\nexport type UnlitMaterialProps = {\n children?: React.ReactNode\n id: string // user id\n} & SpatialUnlitMaterialOptions\n\nexport const UnlitMaterial: React.FC<UnlitMaterialProps> = ({\n children,\n ...options\n}) => {\n const ctx = useRealityContext()\n const materialRef = useRef<SpatialUnlitMaterial | undefined>(undefined)\n const [isInitialized, setIsInitialized] = useState(false)\n const [textureRevision, setTextureRevision] = useState(0)\n\n useEffect(() => {\n if (!ctx || !options.textureId) return\n return ctx.resourceRegistry.subscribe(options.textureId, () => {\n setTextureRevision(v => v + 1)\n })\n }, [ctx, options.textureId])\n\n useEffect(() => {\n if (!ctx) return\n let cancelled = false\n const materialId = options.id\n const { session, resourceRegistry } = ctx\n const init = async () => {\n try {\n let textureIdForNative: string | undefined = options.textureId\n if (options.textureId && resourceRegistry.has(options.textureId)) {\n try {\n const textureResource = await resourceRegistry.get(\n options.textureId,\n )\n if (cancelled) return\n textureIdForNative = textureResource.id\n } catch {\n // failed texture → tint-only\n textureIdForNative = ''\n }\n } else if (options.textureId) {\n // no Texture for this id yet → tint-only; subscribe picks up add() later\n textureIdForNative = ''\n }\n if (cancelled) return\n const commandOptions: SpatialUnlitMaterialOptions = {\n color: options.color,\n textureId: textureIdForNative,\n transparent: options.transparent,\n opacity: options.opacity,\n }\n const materialPromise = session.createUnlitMaterial(commandOptions)\n resourceRegistry.add(materialId, materialPromise)\n const mat = await materialPromise\n if (cancelled) return\n materialRef.current = mat\n setIsInitialized(true)\n } catch (error) {\n console.error(' ~ UnlitMaterial ~ error:', error)\n }\n }\n init()\n\n return () => {\n cancelled = true\n // Use registry to schedule destruction after promise resolves\n resourceRegistry.removeAndDestroy(materialId)\n materialRef.current = undefined\n setIsInitialized(false)\n }\n }, [ctx, options.id])\n\n // Dynamic property updates\n useEffect(() => {\n if (!ctx || !isInitialized || !materialRef.current) return\n let cancelled = false\n void (async () => {\n const updates: Partial<SpatialUnlitMaterialOptions> = {}\n if (options.color !== undefined) updates.color = options.color\n if (options.transparent !== undefined)\n updates.transparent = options.transparent\n if (options.opacity !== undefined) updates.opacity = options.opacity\n if (options.textureId !== undefined) {\n if (options.textureId === '') {\n updates.textureId = ''\n } else if (!ctx.resourceRegistry.has(options.textureId)) {\n updates.textureId = ''\n } else {\n const texturePromise = ctx.resourceRegistry.get(options.textureId)\n try {\n const textureResource = await texturePromise\n if (cancelled) return\n updates.textureId = textureResource.id\n } catch {\n updates.textureId = ''\n }\n }\n }\n if (cancelled || Object.keys(updates).length === 0) return\n const mat = materialRef.current\n if (mat) {\n void mat.updateProperties(updates).catch(() => {})\n }\n })()\n return () => {\n cancelled = true\n }\n }, [\n ctx,\n isInitialized,\n options.color,\n options.textureId,\n options.transparent,\n options.opacity,\n textureRevision,\n ])\n\n return null\n}\n","import React, { useEffect, useRef } from 'react'\nimport { SpatialTextureResource } from '@webspatial/core-sdk'\nimport { useRealityContext } from '../context'\nimport { getAbsoluteUrl } from '../../internal/urlUtils'\n\nexport type TextureProps = {\n children?: React.ReactNode\n id: string\n url: string\n onLoad?: () => void\n onError?: (error: unknown) => void\n}\n\nexport const Texture: React.FC<TextureProps> = ({\n children,\n id,\n url,\n onLoad,\n onError,\n}) => {\n const ctx = useRealityContext()\n const textureRef = useRef<SpatialTextureResource | null>(null)\n const urlRevisionRef = useRef(0)\n\n // Destroy only when the logical texture slot (ctx + id) goes away — not on url changes.\n useEffect(() => {\n if (!ctx) return\n const { resourceRegistry } = ctx\n const capturedId = id\n return () => {\n textureRef.current = null\n resourceRegistry.removeAndDestroy(capturedId)\n }\n }, [ctx, id])\n\n // Initial load and subsequent URL changes: keep the same native texture and use\n // updateProperties({ url }) so materials bound by native id stay valid.\n useEffect(() => {\n if (!ctx) return\n const { session, resourceRegistry } = ctx\n const revision = ++urlRevisionRef.current\n let cancelled = false\n\n void (async () => {\n const resolvedUrl = getAbsoluteUrl(url)\n try {\n if (textureRef.current) {\n await textureRef.current.updateProperties({ url: resolvedUrl })\n\n if (cancelled || revision !== urlRevisionRef.current) return\n\n resourceRegistry.notify(id)\n onLoad?.()\n return\n }\n\n const texturePromise = session.createTexture({ url: resolvedUrl })\n resourceRegistry.add(id, texturePromise)\n\n const tex = await texturePromise\n\n if (cancelled || revision !== urlRevisionRef.current) {\n tex.destroy()\n return\n }\n\n textureRef.current = tex\n onLoad?.()\n } catch (error: unknown) {\n if (cancelled || revision !== urlRevisionRef.current) return\n onError?.(error)\n }\n })()\n\n return () => {\n cancelled = true\n }\n }, [ctx, id, url])\n\n return null\n}\n","/**\n * Internal URL helper used by the spatial implementation (`Texture.tsx`,\n * `ModelAsset.tsx`) to feed the native bridge absolute asset URLs.\n *\n * Resolve asset URLs for the native bridge: relative paths become absolute\n * against the current document (typical dev server is `http://localhost/...`).\n *\n * With no `window` (SSR), returns `url` unchanged — pass absolute `http(s)`\n * URLs if needed.\n *\n * NOT part of the public surface — there is no `export` from\n * `src/index.ts` or `src/eager.ts` reaching this module. Live here under\n * `src/internal/` to make that contract obvious to readers and to keep\n * the file out of any future \"what does the package surface look like?\"\n * audit. Was previously published as `getAbsoluteUrl` from the default\n * entry in v1 (briefly with an `@deprecated` JSDoc); the public export\n * is removed in v2 — see the corresponding changeset for the migration\n * recipe (`new URL(url, location.href).href` for browser callers,\n * framework URL helpers for server-side absolute URLs).\n */\nexport function getAbsoluteUrl(url: string): string {\n if (typeof window === 'undefined' || !window.location?.href) {\n return url\n }\n try {\n return new URL(url, window.location.href).href\n } catch {\n return url\n }\n}\n","import React, { forwardRef } from 'react'\nimport { EntityProps } from '../type'\nimport { EntityRefShape } from '../hooks'\nimport { SpatialSphereGeometryOptions } from '@webspatial/core-sdk'\nimport { GeometryEntity } from './GeometryEntity'\nimport { useRealityContext } from '../context'\n\ntype SphereEntityProps = EntityProps & {\n children?: React.ReactNode\n materials?: string[]\n} & SpatialSphereGeometryOptions\n\nexport const SphereEntity = forwardRef<EntityRefShape, SphereEntityProps>(\n ({ children, ...props }, ref) => {\n const ctx = useRealityContext()\n return (\n <GeometryEntity\n {...props}\n ref={ref}\n createGeometry={options => ctx!.session.createSphereGeometry(options)}\n geometryOptions={{\n radius: props.radius,\n }}\n >\n {children}\n </GeometryEntity>\n )\n },\n)\n","import React, { forwardRef } from 'react'\nimport { EntityProps } from '../type'\nimport { EntityRefShape } from '../hooks'\nimport { SpatialConeGeometryOptions } from '@webspatial/core-sdk'\nimport { GeometryEntity } from './GeometryEntity'\nimport { useRealityContext } from '../context'\n\ntype ConeEntityProps = EntityProps & {\n children?: React.ReactNode\n materials?: string[]\n} & SpatialConeGeometryOptions\n\nexport const ConeEntity = forwardRef<EntityRefShape, ConeEntityProps>(\n ({ children, ...props }, ref) => {\n const ctx = useRealityContext()\n return (\n <GeometryEntity\n {...props}\n ref={ref}\n createGeometry={options => ctx!.session.createConeGeometry(options)}\n geometryOptions={{\n radius: props.radius,\n height: props.height,\n }}\n >\n {children}\n </GeometryEntity>\n )\n },\n)\n","import React, { forwardRef } from 'react'\nimport { EntityProps } from '../type'\nimport { EntityRefShape } from '../hooks'\nimport { SpatialCylinderGeometryOptions } from '@webspatial/core-sdk'\nimport { GeometryEntity } from './GeometryEntity'\nimport { useRealityContext } from '../context'\n\ntype CylinderEntityProps = EntityProps & {\n children?: React.ReactNode\n materials?: string[]\n} & SpatialCylinderGeometryOptions\n\nexport const CylinderEntity = forwardRef<EntityRefShape, CylinderEntityProps>(\n ({ children, ...props }, ref) => {\n const ctx = useRealityContext()\n return (\n <GeometryEntity\n {...props}\n ref={ref}\n createGeometry={options => ctx!.session.createCylinderGeometry(options)}\n geometryOptions={{\n radius: props.radius,\n height: props.height,\n }}\n >\n {children}\n </GeometryEntity>\n )\n },\n)\n","import React, { forwardRef } from 'react'\nimport { EntityProps } from '../type'\nimport { EntityRefShape } from '../hooks'\nimport { SpatialPlaneGeometryOptions } from '@webspatial/core-sdk'\nimport { GeometryEntity } from './GeometryEntity'\nimport { useRealityContext } from '../context'\n\ntype PlaneEntityProps = EntityProps & {\n children?: React.ReactNode\n materials?: string[]\n} & SpatialPlaneGeometryOptions\n\nexport const PlaneEntity = forwardRef<EntityRefShape, PlaneEntityProps>(\n ({ children, ...props }, ref) => {\n const ctx = useRealityContext()\n return (\n <GeometryEntity\n {...props}\n ref={ref}\n createGeometry={options => ctx!.session.createPlaneGeometry(options)}\n geometryOptions={{\n width: props.width,\n height: props.height,\n cornerRadius: props.cornerRadius,\n }}\n >\n {children}\n </GeometryEntity>\n )\n },\n)\n","import React from 'react'\nimport { ParentContext } from '../context'\ntype Props = {\n children?: React.ReactNode\n}\nexport const SceneGraph: React.FC<Props> = ({ children }) => {\n return (\n <ParentContext.Provider value={null}>{children}</ParentContext.Provider>\n )\n}\n","import React, { useEffect, useRef } from 'react'\nimport { useRealityContext } from '../context'\nimport { SpatialModelAsset } from '@webspatial/core-sdk'\nimport { getAbsoluteUrl } from '../../internal/urlUtils'\n\ntype Props = {\n children?: React.ReactNode\n id: string // user id\n src: string // model url\n onLoad?: () => void\n onError?: (error: unknown) => void\n}\n\nexport const ModelAsset: React.FC<Props> = ({ children, ...options }) => {\n const ctx = useRealityContext()\n const materialRef = useRef<SpatialModelAsset | undefined>(undefined)\n useEffect(() => {\n const controller = new AbortController()\n if (!ctx) return\n const { session, resourceRegistry } = ctx\n const init = async () => {\n try {\n const resolvedUrl = getAbsoluteUrl(options.src)\n const modelAssetPromise = session.createModelAsset({ url: resolvedUrl })\n resourceRegistry.add(options.id, modelAssetPromise)\n\n const mat = await modelAssetPromise\n if (controller.signal.aborted) {\n mat.destroy()\n return\n }\n materialRef.current = mat\n options.onLoad?.()\n } catch (error: any) {\n options.onError?.(error)\n }\n }\n init()\n\n return () => {\n controller.abort()\n materialRef.current?.destroy()\n }\n }, [ctx])\n\n return null\n}\n","import React, { forwardRef, useEffect, useRef } from 'react'\nimport {\n SpatialMaterial,\n SpatialModelEntity as CoreSpatialModelEntity,\n} from '@webspatial/core-sdk'\nimport { EntityProps, EntityEventHandler } from '../type'\nimport { EntityRefShape } from '../hooks'\nimport { BaseEntity } from './BaseEntity'\nimport { useRealityContext } from '../context'\nimport { shallowEqualArray } from '../utils'\n\ntype Props = EntityProps & {\n model: string\n materials?: string[]\n} & EntityEventHandler & {\n children?: React.ReactNode\n }\n\nexport const ModelEntity = forwardRef<EntityRefShape, Props>(\n ({ id, model, children, name, materials, ...rest }, ref) => {\n const ctx = useRealityContext()\n const entityRef = useRef<CoreSpatialModelEntity | null>(null)\n const lastMaterialsRef = useRef<string[] | undefined>(undefined)\n\n // TODO(P2): Material overrides run async (`Promise.all` + `setMaterials`) with no generation/abort\n // guard; a slower resolve can apply after a newer prop update and leave native materials stale vs\n // React. Mirror `rebuildGen` in GeometryEntity so only the latest apply runs after awaits.\n // Dynamic material override (including clearing: props may go from ids to undefined / [])\n useEffect(() => {\n if (!ctx || !entityRef.current) return\n const next = materials ?? []\n const prev = lastMaterialsRef.current ?? []\n if (shallowEqualArray(prev, next)) return\n lastMaterialsRef.current = next\n\n const apply = async () => {\n try {\n const materialList = (\n await Promise.all(next.map(mid => ctx.resourceRegistry.get(mid)))\n ).filter(Boolean) as SpatialMaterial[]\n if (entityRef.current) {\n await entityRef.current.setMaterials(materialList)\n }\n } catch (error) {\n console.error('ModelEntity: failed to set materials', error)\n }\n }\n apply()\n }, [ctx, materials])\n\n return (\n <BaseEntity\n {...rest}\n id={id}\n ref={ref}\n recreateKey={model}\n createEntity={async (ctx, signal) => {\n try {\n const modelAsset = await ctx!.resourceRegistry.get(model)\n if (!modelAsset)\n throw new Error(`ModelEntity: model not found ${model}`)\n if (signal.aborted) return null as any\n\n const ent = await ctx!.session.createSpatialModelEntity(\n {\n modelAssetId: modelAsset.id,\n name,\n },\n { id, name },\n )\n entityRef.current = ent as CoreSpatialModelEntity\n\n // Apply initial materials if specified; always record baseline for later clears.\n if (materials && materials.length > 0) {\n const materialList = (\n await Promise.all(\n materials.map(mid => ctx!.resourceRegistry.get(mid)),\n )\n ).filter(Boolean) as SpatialMaterial[]\n if (materialList.length > 0 && !signal.aborted) {\n await ent.setMaterials(materialList)\n }\n }\n lastMaterialsRef.current = materials ?? []\n\n return ent\n } catch (error) {\n return null as any\n }\n }}\n >\n {children}\n </BaseEntity>\n )\n },\n)\n","import React, {\n forwardRef,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from 'react'\nimport { SpatializedContainer } from '../../spatialized-container/SpatializedContainer'\nimport { RealityContext, RealityContextValue } from '../context'\nimport { useInsideAttachment } from '../context/InsideAttachmentContext'\nimport { getSession } from '../../utils/getSession'\nimport { ResourceRegistry } from '../utils'\nimport { AttachmentRegistry } from '../context/AttachmentContext'\nimport { SpatializedElementRef } from '../../spatialized-container/types'\nimport { SpatializedElement } from '@webspatial/core-sdk'\nimport type { SpatializedMotionBinding } from '../../spatialized-container/motion/motionBindingTypes'\nimport { EntityEventHandler } from '../type'\nimport { useRealityEvents } from '../hooks'\nimport { markWebSpatialPrimitive } from '../../jsx/primitive-marker'\n\nexport type RealityProps = Omit<\n React.ComponentPropsWithRef<'div'>,\n 'onSpatialContentReady'\n> &\n EntityEventHandler & {\n /** Native root-transform motion on the Reality container (`SpatializedDynamic3DElement`). */\n 'xr-animation'?: SpatializedMotionBinding\n }\n\nexport const Reality = forwardRef<SpatializedElementRef, RealityProps>(\n function RealityBase({ children, ...inProps }, ref) {\n const insideAttachment = useInsideAttachment()\n if (insideAttachment) {\n console.warn(\n '[WebSpatial] Reality cannot be used inside AttachmentAsset.',\n )\n return null\n }\n const {\n onSpatialTap,\n onSpatialDragStart,\n onSpatialDrag,\n onSpatialDragEnd,\n onSpatialRotate,\n onSpatialRotateEnd,\n onSpatialMagnify,\n onSpatialMagnifyEnd,\n 'xr-animation': xrAnimation,\n ...props\n } = inProps\n const ctxRef = useRef<RealityContextValue | null>(null)\n\n const creationId = useRef(0)\n\n const [isReady, setIsReady] = useState(false)\n\n const cleanupReality = useCallback(() => {\n ctxRef.current?.attachmentRegistry.destroy()\n ctxRef.current?.resourceRegistry.destroy()\n ctxRef.current?.reality.destroy()\n ctxRef.current = null\n setIsReady(false)\n }, [])\n\n useEffect(() => {\n return () => {\n creationId.current++\n cleanupReality()\n }\n }, [cleanupReality])\n\n const createReality = useCallback(async () => {\n const id = ++creationId.current\n const resourceRegistry = new ResourceRegistry()\n const attachmentRegistry = new AttachmentRegistry()\n const session = getSession()\n if (!session) {\n resourceRegistry.destroy()\n attachmentRegistry.destroy()\n return null\n }\n\n const reality = await session.createSpatializedDynamic3DElement()\n\n const isCancelled = () => id !== creationId.current\n\n if (isCancelled()) {\n resourceRegistry.destroy()\n attachmentRegistry.destroy()\n reality.destroy()\n return null\n }\n\n try {\n const result = await session\n .getSpatialScene()\n .addSpatializedElement(reality)\n\n if (!result.success || isCancelled()) {\n resourceRegistry.destroy()\n attachmentRegistry.destroy()\n reality.destroy()\n return null\n }\n\n cleanupReality()\n\n ctxRef.current = {\n session,\n reality,\n resourceRegistry,\n attachmentRegistry,\n }\n setIsReady(true)\n return reality as SpatializedElement\n } catch (err) {\n console.error('[createReality] failed', err)\n resourceRegistry.destroy()\n attachmentRegistry.destroy()\n reality.destroy()\n return null\n }\n }, [cleanupReality])\n\n const content = useCallback(() => <></>, [])\n\n useRealityEvents({\n instance: ctxRef.current?.reality ?? null,\n onSpatialTap,\n onSpatialDragStart,\n onSpatialDrag,\n onSpatialDragEnd,\n onSpatialRotate,\n onSpatialRotateEnd,\n onSpatialMagnify,\n onSpatialMagnifyEnd,\n })\n\n return (\n <RealityContext.Provider value={ctxRef.current}>\n <SpatializedContainer<SpatializedElementRef>\n component=\"div\"\n ref={ref}\n xr-animation={xrAnimation}\n // @ts-ignore\n createSpatializedElement={createReality}\n spatializedContent={content}\n {...props}\n />\n {isReady && children}\n </RealityContext.Provider>\n )\n },\n)\n// Brand the real implementation too: the eager entry exports THIS `Reality`,\n// and the JSX runtime must short-circuit it rather than wrapping it.\nmarkWebSpatialPrimitive(Reality, 'Reality')\n","import React, { useEffect, useState } from 'react'\nimport { createPortal } from 'react-dom'\nimport { useRealityContext } from '../context'\nimport type { ContainerEntry } from '../context/AttachmentContext'\nimport { InsideAttachmentContext } from '../context/InsideAttachmentContext'\n\ntype AttachmentAssetProps = {\n name: string\n children?: React.ReactNode\n}\n\nexport const AttachmentAsset: React.FC<AttachmentAssetProps> = ({\n name,\n children,\n}) => {\n const ctx = useRealityContext()\n const [containers, setContainers] = useState<ContainerEntry[]>([])\n\n useEffect(() => {\n if (!ctx) return\n return ctx.attachmentRegistry.onContainersChange(name, setContainers)\n }, [ctx, name])\n\n if (!containers.length) return null\n return (\n <InsideAttachmentContext.Provider value={true}>\n {containers.map(({ instanceId, container }) =>\n createPortal(children, container, instanceId),\n )}\n </InsideAttachmentContext.Provider>\n )\n}\n","import React, { useEffect, useRef, useState } from 'react'\nimport { Attachment } from '@webspatial/core-sdk'\n\nimport { useRealityContext, useParentContext } from '../context'\nimport { setOpenWindowStyle } from '../../utils/windowStyleSync'\nimport { useSyncHeadStyles } from '../../utils/useSyncHeadStyles'\n\nlet instanceCounter = 0\n\ntype AttachmentEntityProps = {\n attachment: string\n position?: [number, number, number]\n size: { width: number; height: number }\n}\n\nexport const AttachmentEntity: React.FC<AttachmentEntityProps> = ({\n attachment: attachmentName,\n position,\n size,\n}) => {\n const ctx = useRealityContext()\n const parent = useParentContext()\n const attachmentRef = useRef<Attachment | null>(null)\n const parentIdRef = useRef<string | null>(null)\n const instanceIdRef = useRef(`att_${++instanceCounter}`)\n const attachmentNameRef = useRef(attachmentName)\n const [childWindow, setChildWindow] = useState<WindowProxy | null>(null)\n\n // Create the attachment when the parent entity is ready\n useEffect(() => {\n if (!ctx || !parent) return\n\n if (attachmentRef.current) return\n\n const parentId = parent.id\n parentIdRef.current = parentId\n\n let cancelled = false\n\n const init = async () => {\n try {\n const att = await ctx.session.createAttachmentEntity({\n parentEntityId: parentId,\n position: position ?? [0, 0, 0],\n size,\n ownerViewId: ctx.reality.id,\n })\n if (cancelled) {\n att.destroy()\n return\n }\n // Initial style sync for attachment window\n const windowProxy = att.getWindowProxy()\n setOpenWindowStyle(windowProxy)\n // setOpenWindowStyle() above applies SpatialDiv defaults (inline-block, fit-content)\n // which shrink the body to its content. Attachments need the opposite — the body\n // must fill the RealityKit attachment frame — so override to block/100%.\n windowProxy.document.body.style.display = 'block'\n windowProxy.document.body.style.minWidth = '100%'\n windowProxy.document.body.style.maxWidth = '100%'\n windowProxy.document.body.style.minHeight = '100%'\n\n // Ensure viewport meta\n const viewport = windowProxy.document.querySelector(\n 'meta[name=\"viewport\"]',\n )\n if (!viewport) {\n const meta = windowProxy.document.createElement('meta')\n meta.name = 'viewport'\n meta.content =\n 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'\n windowProxy.document.head.appendChild(meta)\n }\n\n // Ensure base href for relative URLs\n const base = windowProxy.document.createElement('base')\n base.href = document.baseURI\n windowProxy.document.head.appendChild(base)\n\n attachmentRef.current = att\n setChildWindow(windowProxy)\n ctx.attachmentRegistry.addContainer(\n attachmentNameRef.current,\n instanceIdRef.current,\n att.getContainer(),\n )\n } catch (error) {\n console.error('[AttachmentEntity] init error:', error)\n }\n }\n\n init()\n\n return () => {\n cancelled = true\n const att = attachmentRef.current\n if (att) {\n ctx.attachmentRegistry.removeContainer(\n attachmentNameRef.current,\n instanceIdRef.current,\n )\n att.destroy()\n attachmentRef.current = null\n setChildWindow(null)\n }\n }\n }, [ctx, parent])\n\n // If attachment name changes at runtime, migrate the container mapping\n useEffect(() => {\n if (!ctx) return\n const att = attachmentRef.current\n const prevName = attachmentNameRef.current\n if (att && prevName !== attachmentName) {\n ctx.attachmentRegistry.removeContainer(prevName, instanceIdRef.current)\n ctx.attachmentRegistry.addContainer(\n attachmentName,\n instanceIdRef.current,\n att.getContainer(),\n )\n attachmentNameRef.current = attachmentName\n } else {\n attachmentNameRef.current = attachmentName\n }\n }, [ctx, attachmentName])\n\n useSyncHeadStyles(childWindow)\n\n // Update position/size when they change\n useEffect(() => {\n if (!attachmentRef.current) return\n attachmentRef.current.update({ position, size })\n }, [position?.[0], position?.[1], position?.[2], size?.width, size?.height])\n\n return null\n}\n","import React from 'react'\nimport { UnlitMaterial, UnlitMaterialProps } from './UnlitMaterial'\n\nexport type MaterialProps = { type: 'unlit' } & UnlitMaterialProps\n\nexport const Material: React.FC<MaterialProps> = props => {\n if (props.type === 'unlit') {\n const { type, ...rest } = props\n return <UnlitMaterial {...rest} />\n }\n return null\n}\n","import { useSyncExternalStore } from 'react'\nimport { PhysicalMetrics } from '@webspatial/core-sdk'\n\nexport function useMetrics() {\n useSyncExternalStore(PhysicalMetrics.subscribe, PhysicalMetrics.getValue)\n const { pointToPhysical, physicalToPoint } = PhysicalMetrics\n return { pointToPhysical, physicalToPoint }\n}\n","import React, { forwardRef, Ref } from 'react'\nimport { SpatialMonitor } from './SpatialMonitor'\n\nconst cachedWithSpatialMonitorType = new Map()\n\nexport function withSpatialMonitor(El: React.ElementType) {\n if (cachedWithSpatialMonitorType.has(El)) {\n return cachedWithSpatialMonitorType.get(El)\n } else {\n const WithSpatialMonitorComponent = forwardRef(\n (givenProps: any, givenRef: Ref<any>) => {\n const {\n El: _,\n\n ...props\n } = givenProps\n\n return <SpatialMonitor El={El} {...props} ref={givenRef} />\n },\n )\n WithSpatialMonitorComponent.displayName = `WithSpatialMonitor(${typeof El === 'string' ? El : El.displayName || El.name})`\n\n cachedWithSpatialMonitorType.set(El, WithSpatialMonitorComponent)\n cachedWithSpatialMonitorType.set(\n cachedWithSpatialMonitorType,\n cachedWithSpatialMonitorType,\n )\n return WithSpatialMonitorComponent\n }\n}\n","import { useRef, useEffect, ForwardedRef, useMemo } from 'react'\nimport { notifyDOMUpdate } from '../notifyUpdateStandInstanceLayout'\n\nexport function useMonitorDomChange(inRef: ForwardedRef<HTMLElement>) {\n const ref = useRef<HTMLElement>(null)\n\n useEffect(() => {\n const observer = new MutationObserver(mutationsList => {\n notifyDOMUpdate(mutationsList)\n })\n\n const config = {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['style', 'class'],\n }\n\n ref.current && observer.observe(ref.current, config)\n\n return () => {\n observer.disconnect()\n }\n }, [])\n\n const proxyRef = useMemo(\n () =>\n new Proxy(ref, {\n set: function (target, key, value) {\n if (key === 'current') {\n if (inRef) {\n if (typeof inRef === 'function') {\n inRef(value)\n } else if (inRef) {\n inRef.current = value\n }\n }\n }\n return Reflect.set(target, key, value)\n },\n }),\n [],\n )\n\n return proxyRef\n}\n","import { useEffect } from 'react'\nimport { notifyUpdateStandInstanceLayout } from '../notifyUpdateStandInstanceLayout'\n\nexport function useMonitorDocumentHeaderChange() {\n useEffect(() => {\n const observer = new MutationObserver(mutationsList => {\n notifyUpdateStandInstanceLayout()\n })\n\n const config = {\n childList: true,\n subtree: true,\n attributes: true,\n }\n\n observer.observe(document.head, config)\n\n return () => {\n observer.disconnect()\n }\n }, [])\n}\n","import { useMonitorDomChange } from './useMonitorDomChange'\nimport { useMonitorDocumentHeaderChange } from './useMonitorDocumentHeaderChange'\nimport { ElementType, ForwardedRef, forwardRef } from 'react'\n\ntype SpatialMonitorProps = {\n El?: ElementType\n}\n\n/**\n * Component that add MutationObserver to monitor all dom changes including its children.\n * If any dom changes, it will notify all SpatialDiv to render again for the purpose of sync standInstance layout to portalInstance.\n */\nfunction SpatialMonitorBase(\n inProps: SpatialMonitorProps,\n inRef: ForwardedRef<HTMLElement>,\n) {\n const { El = 'div', ...props } = inProps\n const ref = useMonitorDomChange(inRef)\n useMonitorDocumentHeaderChange()\n\n return <El {...props} ref={ref} />\n}\n\nexport const SpatialMonitor = forwardRef(SpatialMonitorBase)\n"],"mappings":"yJAAA,o2BAiCA,MAAO,yCCjCP,OACE,WACA,gBACA,UACA,gBAEK,QCNP,OAAS,kBAAqB,QCAvB,IAAM,UAAY,kBDKlB,IAAM,2BAAN,KAEL,CACA,IAA0B,KAC1B,aAA8B,KAEtB,IAAkC,CAAC,EAEnC,cAA6C,CAAC,EAC9C,2BAA0D,CAAC,EAG3D,eAAmD,CAAC,EAErD,+BAA+B,IAAkB,CACtD,KAAK,IAAM,IACX,KAAK,aAAe,IAAI,aAAa,SAAS,EAC9C,OAAO,OAAO,KAAK,GAAG,EAAE,QAAQ,IAAM,GAAG,CAAC,CAC5C,CAEQ,8BAGJ,CAAC,EACE,iCACL,UACA,2BACA,CACA,KAAK,8BAA8B,SAAS,EA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BA,MAAC,IAAI,GAAG,MAAO,IAAU,CAClC,CAEO,IAAM,eAAiBD,aAAW,kBAAkB,EHN5C,cAAAE,UAAA,oBAdf,IAAM,6BAA+B,IAAI,IAElC,SAAS,mBAAmB,GAAuB,CACxD,GAAI,6BAA6B,IAAI,EAAE,EACrC,OAAO,6BAA6B,IAAI,EAAE,EACrC,CACL,IAAM,4BAA8BC,aAClC,CAAC,WAAiB,WAAuB,CACvC,GAAM,CACJ,GAAI,EAEJ,GAAG,KACL,EAAI,WAEJ,OAAOD,MAAC,gBAAe,GAAS,GAAG,MAAO,IAAK,SAAU,CAC3D,CACF,EACA,mCAA4B,YAAc,sBAAsB,OAAO,IAAO,SAAW,GAAK,GAAG,aAAe,GAAG,IAAI,IAEvH,6BAA6B,IAAI,GAAI,2BAA2B,EAChE,6BAA6B,IAC3B,6BACA,4BACF,EACO,2BACT,CACF,CpEoCI,OAAO,OAAW,KACpB,aAAa","names":["useCallback","useContext","useEffect","useContext","useEffect","useCallback","forwardRef","useCallback","useRef","useCallback","useContext","useEffect","useContext","useCallback","useEffect","headObserver","useInternalRef","useRef","useCallback","cssParserDivContainer","forwardRef","forwardRef","useCallback","useContext","useEffect","useMemo","useState","createContext","useContext","useEffect","createContext","getExtraSpatializedElementProperties","createContext","useCallback","useEffect","useLayoutEffect","useState","sheet","useState","useCallback","useEffect","useLayoutEffect","useEffect","useRef","useState","createSpatializedElement","useEffect","jsx","createSpatializedElement","getExtraSpatializedElementProperties","useContext","useEffect","useCallback","useEffect","useRef","useRef","useEffect","useCallback","createContext","useContext","jsx","jsxs","useContext","useMemo","useState","useCallback","useEffect","createSpatializedElement","getExtraSpatializedElementProperties","forwardRef","createPortal","forwardRef","useCallback","useEffect","useState","useEffect","useEffect","useLayoutEffect","useRef","jsx","useEffect","useState","useCallback","createPortal","forwardRef","forwardRef","useCallback","useContext","useEffect","useMemo","useRef","Fragment","jsx","SpatializedContent","useContext","useRef","useMemo","useEffect","createSpatializedElement","useCallback","forwardRef","forwardRef","jsx","forwardRef","useEffect","useMemo","useRef","supports","supports","useRef","useEffect","useMemo","forwardRef","Spatial","jsx","spatial","forwardRef","forwardRef","forwardRef","createContext","useContext","createContext","useContext","createContext","useContext","useEffect","useRef","useRef","useEffect","useEffect","useRef","createEventProxy","useRef","useEffect","useEffect","useRef","createEventProxy","useRef","useEffect","useEffect","useEffect","useEffect","useRef","useRef","useForceUpdate","useEffect","useCallback","useState","useForceUpdate","useCallback","useEffect","useMemo","useRef","useReducer","useMemo","useRef","useReducer","useCallback","useEffect","jsx","forwardRef","jsx","forwardRef","forwardRef","forwardRef","useEffect","useRef","jsx","forwardRef","useRef","useEffect","ctx","id","jsx","forwardRef","useEffect","useRef","useState","useRef","useState","useEffect","useEffect","useRef","useRef","useEffect","forwardRef","jsx","forwardRef","forwardRef","jsx","forwardRef","forwardRef","jsx","forwardRef","forwardRef","jsx","forwardRef","jsx","useEffect","useRef","useRef","useEffect","forwardRef","useEffect","useRef","jsx","forwardRef","useRef","useEffect","ctx","forwardRef","useCallback","useEffect","useRef","useState","Fragment","jsx","jsxs","forwardRef","useRef","useState","useCallback","useEffect","useEffect","useState","createPortal","jsx","useState","useEffect","createPortal","useEffect","useRef","useState","useRef","useState","useEffect","jsx","forwardRef","useRef","useEffect","useMemo","useRef","useEffect","useMemo","useEffect","useEffect","forwardRef","jsx","jsx","forwardRef"]}
|