@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,19 @@
|
|
|
1
|
+
import{detectSpatialRuntime}from"./chunk-GG2QK5MA.js";import{markWebSpatialPrimitive}from"./chunk-QHUROD77.js";import{__export}from"./chunk-NXEOIP4Z.js";var spatial_exports={};__export(spatial_exports,{AttachmentAsset:()=>AttachmentAsset,AttachmentEntity:()=>AttachmentEntity,Box:()=>BoxEntity,BoxEntity:()=>BoxEntity,Cone:()=>ConeEntity,ConeEntity:()=>ConeEntity,Cylinder:()=>CylinderEntity,CylinderEntity:()=>CylinderEntity,Entity:()=>Entity,Material:()=>Material,Model:()=>Model,ModelAsset:()=>ModelAsset,ModelEntity:()=>ModelEntity,Plane:()=>PlaneEntity,PlaneEntity:()=>PlaneEntity,Reality:()=>Reality,SceneGraph:()=>SceneGraph,Sphere:()=>SphereEntity,SphereEntity:()=>SphereEntity,Texture:()=>Texture,UnlitMaterial:()=>UnlitMaterial,World:()=>SceneGraph,eventMap:()=>eventMap,getSession:()=>getSession,useAnimation:()=>useAnimation,useEntityAnimation:()=>useEntityAnimation,useMetrics:()=>useMetrics,withSpatialMonitor:()=>withSpatialMonitor,withSpatialized2DElementContainer:()=>withSpatialized2DElementContainer});import"@webspatial/core-sdk/install-polyfills";import{useContext,useLayoutEffect,useEffect,useCallback}from"react";import{createContext}from"react";var SpatialID="data-spatial-id";var SpatializedContainerObject=class{dom=null;domSpatialId=null;fns={};spatialId2dom={};spatialId2parentSpatialDom={};layerSequences={};notify2DFramePlaceHolderChange(dom){this.dom=dom,this.domSpatialId=dom.getAttribute(SpatialID),Object.values(this.fns).forEach(fn=>fn())}spatialId2transformVisibility={};updateSpatialTransformVisibility(spatialId,spatialTransformVisibility){this.spatialId2transformVisibility[spatialId]=spatialTransformVisibility,this.fnsForSpatialTransformVisibility[spatialId]?.forEach(fn=>fn(spatialTransformVisibility))}spatialId2ContainerRefProxy={};updateSpatialContainerRefProxyInfo(spatialId,spatialContainerRefProxy){this.spatialId2ContainerRefProxy[spatialId]=spatialContainerRefProxy}getSpatialContainerRefProxyBySpatialId(spatialId){return this.spatialId2ContainerRefProxy[spatialId]}fnsForSpatialTransformVisibility={};onSpatialTransformVisibilityChange(spatialId,fn){this.fnsForSpatialTransformVisibility[spatialId]||(this.fnsForSpatialTransformVisibility[spatialId]=[]),this.fnsForSpatialTransformVisibility[spatialId].push(fn),this.spatialId2transformVisibility[spatialId]&&fn(this.spatialId2transformVisibility[spatialId])}offSpatialTransformVisibilityChange(spatialId,fn){let fns=this.fnsForSpatialTransformVisibility[spatialId];fns&&(this.fnsForSpatialTransformVisibility[spatialId]=fns.filter(f=>f!==fn))}on2DFrameChange(spatialId,fn){this.fns[spatialId]=fn,this.dom&&fn()}off2DFrameChange(spatialId){delete this.fns[spatialId],delete this.spatialId2dom[spatialId],delete this.spatialId2parentSpatialDom[spatialId]}querySpatialDomBySpatialId(spatialId){if(this.domSpatialId===spatialId)return this.dom;if(!this.dom)return null;if(!this.spatialId2dom[spatialId]){let spatialDom=this.dom.querySelector(`[${SpatialID}="${spatialId}"]`);spatialDom&&(this.spatialId2dom[spatialId]=spatialDom)}return this.spatialId2dom[spatialId]}queryParentSpatialDomBySpatialId(spatialId){if(this.domSpatialId===spatialId)return null;if(this.spatialId2parentSpatialDom[spatialId])return this.spatialId2parentSpatialDom[spatialId];let spatialDom=this.querySpatialDomBySpatialId(spatialId);if(spatialDom){if(spatialDom===this.dom)return null;let parentSpatialDom=spatialDom.parentElement;for(;parentSpatialDom&&spatialDom!==this.dom&&!parentSpatialDom.hasAttribute(SpatialID);)parentSpatialDom=parentSpatialDom.parentElement;return this.spatialId2parentSpatialDom[spatialId]=parentSpatialDom,parentSpatialDom}return null}getSpatialId(layer,isInStandardInstance,name=""){this.layerSequences[layer]===void 0&&(this.layerSequences[layer]=[0,0]);let idx=isInStandardInstance?0:1,sequenceId=this.layerSequences[layer][idx];return this.layerSequences[layer][idx]=sequenceId+1,`${name}_${layer}_${sequenceId}`}},SpatializedContainerContext=createContext(null);function use2DFrameDetector(ref){let spatializedContainerObject=useContext(SpatializedContainerContext),notify2DFrameChange=useCallback(()=>{ref.current&&spatializedContainerObject.notify2DFramePlaceHolderChange(ref.current)},[ref.current,spatializedContainerObject]);useLayoutEffect(notify2DFrameChange,[notify2DFrameChange]),useEffect(()=>{if(!ref.current||!spatializedContainerObject){console.warn("Ref is not attached to the DOM or spatializedContainerObject is not available");return}return window.addEventListener("resize",notify2DFrameChange),()=>{window.removeEventListener("resize",notify2DFrameChange)}},[]),useEffect(()=>{if(!ref.current){console.warn("Ref is not attached to the DOM");return}let ro=new ResizeObserver(notify2DFrameChange);return ro.observe(ref.current),()=>{ro.disconnect()}},[]),useEffect(()=>{if(!ref.current){console.warn("Ref is not attached to the DOM");return}let ro=new MutationObserver(notify2DFrameChange);return ro.observe(ref.current,{attributeFilter:["class","style"],subtree:!0}),()=>{ro.disconnect()}},[])}import{forwardRef,useCallback as useCallback2,useContext as useContext2,useEffect as useEffect2,useRef,useState}from"react";import{jsx}from"react/jsx-runtime";function useSpatialTransformVisibilityWatcher(spatialId){let[transformExist,setTransformExist]=useState(!1),spatializedContainerObject=useContext2(SpatializedContainerContext);return useEffect2(()=>{let fn=spatialTransform=>{setTransformExist(spatialTransform.transform!=="none")};return spatializedContainerObject.onSpatialTransformVisibilityChange(spatialId,fn),()=>{spatializedContainerObject.offSpatialTransformVisibilityChange(spatialId,fn)}},[spatialId,spatializedContainerObject]),transformExist}function useInternalRef(ref){let refInternal=useRef(null),refInternalCallback=useCallback2(node=>{refInternal.current=node,typeof ref=="function"?ref(node):ref&&(ref.current=node)},[ref]);return{refInternal,refInternalCallback}}function StandardSpatializedContainerBase(props,ref){let{component:Component,style:inStyle={},className,inStandardSpatializedContainer=!1,...restProps}=props,{refInternal,refInternalCallback}=useInternalRef(ref);inStandardSpatializedContainer||use2DFrameDetector(refInternal);let transformExist=useSpatialTransformVisibilityWatcher(props[SpatialID]),classNames=className?`${className} xr-spatial-default`:"xr-spatial-default";return jsx(Component,{ref:refInternalCallback,style:inStyle,className:classNames,...restProps,"data-xr-host":"","data-xr-transform-active":transformExist?"":void 0})}var StandardSpatializedContainer=forwardRef(StandardSpatializedContainerBase),SPATIAL_DEFAULT_STYLE_CSS=`
|
|
2
|
+
:where(.xr-spatial-default) {
|
|
3
|
+
--xr-back: 0;
|
|
4
|
+
--xr-depth: 0;
|
|
5
|
+
--xr-z-index: 0;
|
|
6
|
+
--xr-background-material: none;
|
|
7
|
+
}
|
|
8
|
+
.xr-spatial-default[data-xr-host] {
|
|
9
|
+
visibility: hidden !important;
|
|
10
|
+
transition: none !important;
|
|
11
|
+
transform: none !important;
|
|
12
|
+
}
|
|
13
|
+
.xr-spatial-default[data-xr-host][data-xr-transform-active] {
|
|
14
|
+
transform: translateZ(0) !important;
|
|
15
|
+
}
|
|
16
|
+
`,SPATIAL_DEFAULT_STYLE_MARKER="data-xr-spatial-default-style";function ensureSpatialDefaultStyleInRoot(root){if((root===document?document.head:root).querySelector(`style[${SPATIAL_DEFAULT_STYLE_MARKER}]`))return;let styleElement=(root===document?document:root.ownerDocument||document).createElement("style");styleElement.type="text/css",styleElement.setAttribute(SPATIAL_DEFAULT_STYLE_MARKER,""),styleElement.innerHTML=SPATIAL_DEFAULT_STYLE_CSS,root===document?document.head.appendChild(styleElement):root.appendChild(styleElement)}function injectSpatialDefaultStyle(){ensureSpatialDefaultStyleInRoot(document)}import{createElement,forwardRef as forwardRef2,useCallback as useCallback4,useRef as useRef2}from"react";import{createPortal}from"react-dom";import{useCallback as useCallback3,useContext as useContext3,useEffect as useEffect3}from"react";function notifyUpdateStandInstanceLayout(){document.dispatchEvent(new CustomEvent("standInstanceLayout",{detail:{}}))}function notifyDOMUpdate(mutationsList){document.dispatchEvent(new CustomEvent("domUpdated",{detail:mutationsList}))}function parseTransformAndVisibilityProperties(node){let computedStyle=getComputedStyle(node),transform=computedStyle.getPropertyValue("transform");return{visibility:computedStyle.getPropertyValue("visibility"),transform}}function useSpatialTransformVisibility(spatialId,ref){let spatializedContainerObject=useContext3(SpatializedContainerContext),checkSpatialStyleUpdate=useCallback3(()=>{if(!ref.current)return;let spatialTransformVisibility=parseTransformAndVisibilityProperties(ref.current);spatializedContainerObject.updateSpatialTransformVisibility(spatialId,spatialTransformVisibility)},[]);useEffect3(()=>{checkSpatialStyleUpdate()},[checkSpatialStyleUpdate]),useEffect3(()=>{let observer=new MutationObserver(mutationsList=>{checkSpatialStyleUpdate()}),config={childList:!1,subtree:!1,attributes:!0,attributeFilter:["style","class"]};return observer.observe(ref.current,config),()=>{observer.disconnect()}},[]),useEffect3(()=>{let headObserver2=new MutationObserver(mutations=>{checkSpatialStyleUpdate()});return headObserver2.observe(document.head,{childList:!0,subtree:!0}),()=>{headObserver2.disconnect()}},[]),useEffect3(()=>{let onDomUpdated=event=>{checkSpatialStyleUpdate()};return document.addEventListener("domUpdated",onDomUpdated),()=>{document.removeEventListener("domUpdated",onDomUpdated)}},[])}var cssParserDivContainer=null;function initCSSParserDivContainer(){cssParserDivContainer=document?.createElement("div"),cssParserDivContainer&&(cssParserDivContainer.style.position="absolute",cssParserDivContainer.setAttribute("data-id","css-parser-div-container"))}function createOrGetCSSParserDivContainer(){return cssParserDivContainer&&!cssParserDivContainer.parentElement&&document?.body.appendChild(cssParserDivContainer),cssParserDivContainer}function useInternalRef2(ref){let refInternal=useRef2(null),refInternalCallback=useCallback4(node=>{refInternal.current=node,typeof ref=="function"?ref(node):ref&&(ref.current=node)},[ref]);return{refInternal,refInternalCallback}}function resolveProbeIntrinsicTag(component){return typeof component=="string"?component:"div"}function TransformVisibilityTaskContainerBase(props,ref){let{style:inStyle,component,...restProps}=props,ProbeTag=resolveProbeIntrinsicTag(component),extraStyle={left:-1e4,top:-1e4,pointerEvents:"none",opacity:0,padding:0,transition:"none",position:"absolute"},{refInternal,refInternalCallback}=useInternalRef2(ref),style={...inStyle,...extraStyle};useSpatialTransformVisibility(props[SpatialID],refInternal);let cssParserDivContainer2=createOrGetCSSParserDivContainer();return cssParserDivContainer2?createPortal(createElement(ProbeTag,{ref:refInternalCallback,style,...restProps}),cssParserDivContainer2):null}var TransformVisibilityTaskContainer=forwardRef2(TransformVisibilityTaskContainerBase);import{forwardRef as forwardRef3,useCallback as useCallback7,useContext as useContext6,useEffect as useEffect9,useMemo as useMemo2,useState as useState4}from"react";import{isSSREnv,Spatial}from"@webspatial/core-sdk";var spatial=null,_currentSession=null;function getSession(){return isSSREnv()||(spatial||(spatial=new Spatial),!spatial.isSupported())?null:_currentSession||(_currentSession=spatial.requestSession(),_currentSession)}import{createContext as createContext2}from"react";var SpatialLayerContext=createContext2(0);import{useMemo,useContext as useContext4,useEffect as useEffect7}from"react";import{createContext as createContext3}from"react";function getInheritedStyleProps(computedStyle){var propNames=["borderCollapse","borderSpacing","captionSide","color","cursor","direction","emptyCells","fontFamily","fontSize","fontStyle","fontVariant","fontWeight","font","letterSpacing","lineHeight","listStyleImage","listStylePosition","listStyleType","listStyle","orphans","quotes","textAlign","textIndent","textTransform","visibility","whiteSpace","widows","wordSpacing","background","position","width","height","display","contentVisibility"],props={};for(var cssName of propNames)computedStyle[cssName]&&(props[cssName]=computedStyle[cssName]);return props}function parseTransformOrigin(computedStyle){let transformOriginProperty=computedStyle.getPropertyValue("transform-origin"),[x,y]=transformOriginProperty.split(" ").map(parseFloat),width=parseFloat(computedStyle.getPropertyValue("width")),height=parseFloat(computedStyle.getPropertyValue("height"));return{x:width>0?x/width:.5,y:height>0?y/height:.5,z:.5}}function parseBorderRadius(borderProperty,width){return borderProperty===""?0:borderProperty.endsWith("%")?width*parseFloat(borderProperty)/100:parseFloat(borderProperty)}function parseCornerRadius(computedStyle){let width=parseFloat(computedStyle.getPropertyValue("width")),topLeftPropertyValue=computedStyle.getPropertyValue("border-top-left-radius"),topRightPropertyValue=computedStyle.getPropertyValue("border-top-right-radius"),bottomLeftPropertyValue=computedStyle.getPropertyValue("border-bottom-left-radius"),bottomRightPropertyValue=computedStyle.getPropertyValue("border-bottom-right-radius");return{topLeading:parseBorderRadius(topLeftPropertyValue,width),bottomLeading:parseBorderRadius(bottomLeftPropertyValue,width),topTrailing:parseBorderRadius(topRightPropertyValue,width),bottomTrailing:parseBorderRadius(bottomRightPropertyValue,width)}}function extractAndRemoveCustomProperties(cssText,properties){if(!cssText)return{extractedValues:{},filteredCssText:""};let extractedValues={},filteredCssText=cssText.split(";").filter(rule=>{let[key,value]=rule.split(":").map(part=>part.trim());return properties.includes(key)?(extractedValues[key]=value,!1):!0}).join(";").trim();return{extractedValues,filteredCssText}}function joinToCSSText(cssKV){return Object.entries(cssKV).map(([key,value])=>`${key}: ${value}`).join(";")}var SpatialCustomStyleVars={back:"--xr-back",depth:"--xr-depth",backgroundMaterial:"--xr-background-material",xrZIndex:"--xr-z-index"};var PortalInstanceObject=class{spatialId;spatializedContainerObject;parentPortalInstanceObject;spatializedElement;cachedDomInfo;get dom(){return this.cachedDomInfo?.dom}get computedStyle(){return this.cachedDomInfo?.computedStyle}get isFixedPosition(){return this.cachedDomInfo?.isFixedPosition}cachedDomRect;get domRect(){return this.cachedDomRect}cachedTransformVisibilityInfo;get transformMatrix(){return this.cachedTransformVisibilityInfo?.transformMatrix}get visibility(){return this.cachedTransformVisibilityInfo?.visibility}spatializedElementPromise;spatializedElementResolver;getExtraSpatializedElementProperties;constructor(spatialId,spatializedContainerObject,parentPortalInstanceObject,getExtraSpatializedElementProperties2){this.spatialId=spatialId,this.spatializedContainerObject=spatializedContainerObject,this.parentPortalInstanceObject=parentPortalInstanceObject,this.getExtraSpatializedElementProperties=getExtraSpatializedElementProperties2,this.spatializedElementPromise=new Promise(resolve=>{this.spatializedElementResolver=resolve})}init(){this.spatializedContainerObject.onSpatialTransformVisibilityChange(this.spatialId,this.onSpatialTransformVisibilityChange)}destroy(){this.spatializedContainerObject.offSpatialTransformVisibilityChange(this.spatialId,this.onSpatialTransformVisibilityChange)}onSpatialTransformVisibilityChange=spatialTransform=>{this.cachedTransformVisibilityInfo={transformMatrix:new DOMMatrix(spatialTransform.transform),visibility:spatialTransform.visibility},this.updateSpatializedElementProperties()};notify2DFrameChange(){let dom=this.spatializedContainerObject.querySpatialDomBySpatialId(this.spatialId);if(!dom)return;let computedStyle=getComputedStyle(dom);this.cachedDomInfo={dom,computedStyle,isFixedPosition:computedStyle.getPropertyValue("position")==="fixed"},this.updateSpatializedElementProperties(),Object.assign(dom,{__innerSpatializedElement:()=>this.spatializedElement})}async getSpatializedElement(){return this.spatializedElementPromise}attachSpatializedElement(spatializedElement){this.spatializedElement=spatializedElement,this.addToParent(spatializedElement),this.spatializedElementResolver?.(spatializedElement),this.updateSpatializedElementProperties()}inAddingToParent=!1;async addToParent(spatializedElement){if(!this.inAddingToParent){if(this.inAddingToParent=!0,this.isFixedPosition||!this.parentPortalInstanceObject){var spatialScene=await getSession().getSpatialScene();await spatialScene.addSpatializedElement(spatializedElement)}else(await this.parentPortalInstanceObject.getSpatializedElement()).addSpatializedElement(spatializedElement);this.inAddingToParent=!1}}updateSpatializedElementProperties(){let dom=this.dom,spatializedElement=this.spatializedElement,visibility=this.visibility;if(!dom||!spatializedElement||!visibility||!this.transformMatrix)return;let computedStyle=this.computedStyle,isFixedPosition=this.isFixedPosition,domRect=dom.getBoundingClientRect(),{x,y}=domRect;if(!isFixedPosition){let parentDom=this.spatializedContainerObject.queryParentSpatialDomBySpatialId(this.spatialId);if(parentDom){let parentDomRect=parentDom.getBoundingClientRect();x-=parentDomRect.x,y-=parentDomRect.y}else x+=window.scrollX,y+=window.scrollY}this.cachedDomRect={x:domRect.x,y:domRect.y,width:domRect.width,height:domRect.height};let width=domRect.width,height=domRect.height,opacity=parseFloat(computedStyle.getPropertyValue("opacity")),scrollWithParent=!isFixedPosition,display=computedStyle.getPropertyValue("display"),visible=visibility==="visible"&&display!=="none",zIndex=parseFloat(computedStyle.getPropertyValue(SpatialCustomStyleVars.xrZIndex))||0,backOffset=parseFloat(computedStyle.getPropertyValue(SpatialCustomStyleVars.back))||0,depth=parseFloat(computedStyle.getPropertyValue(SpatialCustomStyleVars.depth))||0,rotationAnchor=parseTransformOrigin(computedStyle),extraProperties=this.getExtraSpatializedElementProperties?.(computedStyle)||{};spatializedElement.updateProperties({clientX:x,clientY:y,width,height,depth,opacity,scrollWithParent,zIndex,visible,backOffset,rotationAnchor,...extraProperties}),spatializedElement.updateTransform(this.transformMatrix),Object.assign(this.dom,{__spatializedElement:spatializedElement})}},PortalInstanceContext=createContext3(null);import{useCallback as useCallback5,useEffect as useEffect4,useLayoutEffect as useLayoutEffect2,useState as useState2}from"react";function asyncLoadStyleToChildWindow(childWindow,link,isCurrent){return new Promise(resolve=>{let{href}=link,sep=href.includes("?")?"&":"?";link.href=`${href}${sep}uniqueURL=${Math.random()}`;let finished=!1,finish=ok=>{finished||(finished=!0,resolve(ok))};link.onerror=()=>{finish(!1)},link.onload=()=>{if(!isCurrent()){link.parentNode?.removeChild(link),finish(!1);return}finish(!0)},setTimeout(()=>{if(!isCurrent()){finish(!1);return}childWindow.document.head.appendChild(link)},50)})}var WEBSPATIAL_SYNC_ATTR="data-webspatial-sync",WEBSPATIAL_SYNC_KEY_ATTR="data-webspatial-sync-key";function getStyleElementTextForSync(styleEl){let sheet=styleEl.sheet;if(sheet)try{let parts=[];for(let i=0;i<sheet.cssRules.length;i++)parts.push(sheet.cssRules[i].cssText);if(parts.length>0)return parts.join(`
|
|
17
|
+
`)}catch{}return styleEl.textContent??""}function copyParentStyleAttributes(source,target){let sourceAttrNames=new Set(Array.from(source.attributes,attr=>attr.name));for(let attr of Array.from(target.attributes))attr.name!==WEBSPATIAL_SYNC_ATTR&&(sourceAttrNames.has(attr.name)||target.removeAttribute(attr.name));for(let attr of Array.from(source.attributes))attr.name!==WEBSPATIAL_SYNC_ATTR&&target.setAttribute(attr.name,attr.value)}function cloneParentStyleElementForSync(styleEl){let node=document.createElement("style");return copyParentStyleAttributes(styleEl,node),node.setAttribute(WEBSPATIAL_SYNC_ATTR,"1"),node}function getStyleSheetRuleTexts(styleEl){let sheet=styleEl.sheet;if(!sheet)return null;try{let texts=[];for(let i=0;i<sheet.cssRules.length;i++)texts.push(sheet.cssRules[i].cssText);return texts}catch{return null}}function clearStyleSheetRules(sheet){for(;sheet.cssRules.length>0;)sheet.deleteRule(sheet.cssRules.length-1)}function getStyleTextForRules(source,parentRules){return parentRules&&parentRules.length>0?parentRules.join(`
|
|
18
|
+
`):source.textContent??""}function applyFullTextStyleSync(target,source,text=getStyleElementTextForSync(source)){let sheet=target.sheet;if(sheet)try{clearStyleSheetRules(sheet)}catch{}target.textContent=text}function syncStyleSheetRulesToChild(target,source,precomputedParentRules,precomputedText){let parentRules=precomputedParentRules===void 0?getStyleSheetRuleTexts(source):precomputedParentRules,parentText=precomputedText??getStyleTextForRules(source,parentRules);if(parentRules===null){applyFullTextStyleSync(target,source,parentText);return}if(parentRules.length===0){let sheet2=target.sheet;if(sheet2)try{clearStyleSheetRules(sheet2)}catch{applyFullTextStyleSync(target,source);return}target.textContent!==parentText&&(target.textContent=parentText);return}let sheet=target.sheet;if(!sheet){applyFullTextStyleSync(target,source,parentText);return}try{let commonPrefix=0,maxPrefix=Math.min(sheet.cssRules.length,parentRules.length);for(;commonPrefix<maxPrefix&&sheet.cssRules[commonPrefix].cssText===parentRules[commonPrefix];)commonPrefix++;for(;sheet.cssRules.length>commonPrefix;)sheet.deleteRule(sheet.cssRules.length-1);for(let i=commonPrefix;i<parentRules.length;i++)sheet.insertRule(parentRules[i],i)}catch{applyFullTextStyleSync(target,source,parentText)}}function captureParentHeadSnapshot(){let parentStyles=Array.from(document.head.querySelectorAll("style")),styleRuleTexts=parentStyles.map(getStyleSheetRuleTexts),styleTextContents=parentStyles.map((style,index)=>getStyleTextForRules(style,styleRuleTexts[index])),parentStylesheets=Array.from(document.head.querySelectorAll('link[rel="stylesheet"][href]'));return{parentStyles,parentStylesheets,documentElementClassName:document.documentElement.className,styleRuleTexts,styleTextContents}}function syncInlineStylesToChild(childHead,snapshot){let{parentStyles,styleRuleTexts,styleTextContents}=snapshot,existing=Array.from(childHead.querySelectorAll(`style[${WEBSPATIAL_SYNC_ATTR}="1"]`));for(let i=0;i<parentStyles.length;i++){let source=parentStyles[i],target=existing[i];if(target)copyParentStyleAttributes(source,target),syncStyleSheetRulesToChild(target,source,styleRuleTexts[i],styleTextContents[i]);else{let node=cloneParentStyleElementForSync(source);childHead.appendChild(node),syncStyleSheetRulesToChild(node,source,styleRuleTexts[i],styleTextContents[i])}}for(let i=parentStyles.length;i<existing.length;i++)existing[i].parentNode?.removeChild(existing[i])}function setOpenWindowStyle(openedWindow){openedWindow.document.documentElement.style.cssText+=document.documentElement.style.cssText,openedWindow.document.documentElement.style.backgroundColor="transparent",openedWindow.document.body.style.margin="0px",openedWindow.document.body.style.display="inline-block",openedWindow.document.body.style.minWidth="auto",openedWindow.document.body.style.minHeight="auto",openedWindow.document.body.style.maxWidth="fit-content",openedWindow.document.body.style.minWidth="fit-content",openedWindow.document.body.style.background="transparent"}var controllers=new WeakMap;function getController(childWindow){let prev=controllers.get(childWindow);if(prev)return prev;let next={version:0};return controllers.set(childWindow,next),next}async function syncParentHeadToChild(childWindow,snapshot=captureParentHeadSnapshot()){let controller=getController(childWindow),version=++controller.version,styleLoadedPromises=[],{head}=childWindow.document,isCurrent=()=>controller.version===version,{parentStylesheets}=snapshot,desiredStylesheetKeys=new Set;for(let link of parentStylesheets)link.href&&desiredStylesheetKeys.add(link.href);let existingSyncedLinks=Array.from(head.querySelectorAll(`link[rel="stylesheet"][${WEBSPATIAL_SYNC_ATTR}="1"]`));for(let link of existingSyncedLinks){let key=link.getAttribute(WEBSPATIAL_SYNC_KEY_ATTR)??link.href;desiredStylesheetKeys.has(key)||link.parentNode?.removeChild(link)}syncInlineStylesToChild(head,snapshot);let currentKeys=new Set,currentSyncedLinks=Array.from(head.querySelectorAll(`link[rel="stylesheet"][${WEBSPATIAL_SYNC_ATTR}="1"]`));for(let link of currentSyncedLinks)currentKeys.add(link.getAttribute(WEBSPATIAL_SYNC_KEY_ATTR)??link.href);for(let link of parentStylesheets){let key=link.href;if(!key||currentKeys.has(key))continue;let node=link.cloneNode(!0);node.setAttribute(WEBSPATIAL_SYNC_ATTR,"1"),node.setAttribute(WEBSPATIAL_SYNC_KEY_ATTR,key),styleLoadedPromises.push(asyncLoadStyleToChildWindow(childWindow,node,isCurrent))}return childWindow.document.documentElement.className=snapshot.documentElementClassName,Promise.all(styleLoadedPromises)}var headSyncSchedulers=new WeakMap;function getHeadSyncScheduler(childWindow){let prev=headSyncSchedulers.get(childWindow);if(prev)return prev;let next={disposed:!1};return headSyncSchedulers.set(childWindow,next),next}var activeTargets=new Set,headObserver=null,domUpdatedHandler=null,originalInsertRule,originalDeleteRule,pendingWave=null,flushQueued=null,delayTimer,afterHostLayoutRaf,timingPriority={delayed:1,afterHostLayout:2,immediate:3};function isParentHeadStyleSheet(sheet){let ownerNode=sheet.ownerNode;return ownerNode instanceof HTMLStyleElement&&ownerNode.ownerDocument===document&&document.head.contains(ownerNode)?!0:Array.from(document.head.querySelectorAll("style")).some(style=>style.sheet===sheet)}function getSyncTiming(mutations){if(!Array.isArray(mutations)||mutations.length===0)return null;let hasDelayed=!1;for(let mutation of mutations){if(mutation.type==="characterData"&&mutation.target.parentElement?.tagName==="STYLE")return"immediate";let nodes=[mutation.target,...Array.from(mutation.addedNodes),...Array.from(mutation.removedNodes)];for(let node of nodes){if(!(node instanceof Element))continue;let tag=node.tagName;if(tag==="STYLE")return"immediate";if(tag==="LINK"){let{rel}=node;rel&&rel.toLowerCase()==="stylesheet"&&(hasDelayed=!0)}}}return hasDelayed?"delayed":null}function installCssomRuleObserver(){typeof CSSStyleSheet>"u"||originalInsertRule||(originalInsertRule=CSSStyleSheet.prototype.insertRule,originalDeleteRule=CSSStyleSheet.prototype.deleteRule,CSSStyleSheet.prototype.insertRule=function(rule,index){let result=originalInsertRule.call(this,rule,index);return isParentHeadStyleSheet(this)&&enqueueParentHeadSync("immediate",{broadcast:!0}),result},CSSStyleSheet.prototype.deleteRule=function(index){originalDeleteRule.call(this,index),isParentHeadStyleSheet(this)&&enqueueParentHeadSync("immediate",{broadcast:!0})})}function uninstallCssomRuleObserver(){originalInsertRule&&(CSSStyleSheet.prototype.insertRule=originalInsertRule),originalDeleteRule&&(CSSStyleSheet.prototype.deleteRule=originalDeleteRule),originalInsertRule=void 0,originalDeleteRule=void 0}function installParentHeadSyncRegistry(){headObserver||(headObserver=new MutationObserver(mutations=>{let timing=getSyncTiming(mutations);timing&&enqueueParentHeadSync(timing,{broadcast:!0})}),headObserver.observe(document.head,{childList:!0,characterData:!0,subtree:!0})),domUpdatedHandler||(domUpdatedHandler=()=>enqueueParentHeadSync("afterHostLayout",{broadcast:!0}),document.addEventListener("domUpdated",domUpdatedHandler)),installCssomRuleObserver()}function clearQueuedFlush(){delayTimer&&(window.clearTimeout(delayTimer),delayTimer=void 0),afterHostLayoutRaf&&(window.cancelAnimationFrame(afterHostLayoutRaf),afterHostLayoutRaf=void 0),flushQueued=null}function teardownParentHeadSyncRegistry(){headObserver?.disconnect(),headObserver=null,domUpdatedHandler&&(document.removeEventListener("domUpdated",domUpdatedHandler),domUpdatedHandler=null),uninstallCssomRuleObserver(),clearQueuedFlush(),pendingWave=null}function teardownParentHeadSyncRegistryIfEmpty(){activeTargets.size>0||teardownParentHeadSyncRegistry()}function isWindowDisposed(childWindow){return headSyncSchedulers.get(childWindow)?.disposed===!0}function getOrCreatePendingWave(timing){return pendingWave?(timingPriority[timing]>timingPriority[pendingWave.timing]&&(pendingWave.timing=timing),pendingWave):(pendingWave={timing,broadcast:!1,targets:new Set,onComplete:new Map},pendingWave)}async function flushHeadSyncWave(){let wave=pendingWave;if(pendingWave=null,flushQueued=null,delayTimer=void 0,afterHostLayoutRaf=void 0,!wave)return;let targets=(wave.broadcast?Array.from(activeTargets):Array.from(wave.targets)).filter(childWindow=>!isWindowDisposed(childWindow));if(targets.length===0)return;let snapshot=captureParentHeadSnapshot();await Promise.all(targets.map(async childWindow=>{await syncParentHeadToChild(childWindow,snapshot),wave.onComplete.get(childWindow)?.()}))}function queuePendingWaveFlush(timing){if(timing==="delayed"){if(flushQueued)return;flushQueued="delayed",delayTimer=window.setTimeout(()=>{flushHeadSyncWave()},100);return}if(delayTimer&&(window.clearTimeout(delayTimer),delayTimer=void 0),timing==="immediate"){if(afterHostLayoutRaf&&(window.cancelAnimationFrame(afterHostLayoutRaf),afterHostLayoutRaf=void 0),flushQueued==="immediate")return;flushQueued="immediate",queueMicrotask(()=>{flushQueued==="immediate"&&flushHeadSyncWave()});return}flushQueued==="immediate"||flushQueued==="afterHostLayout"||(flushQueued="afterHostLayout",queueMicrotask(()=>{flushQueued==="afterHostLayout"&&(afterHostLayoutRaf=window.requestAnimationFrame(()=>{flushQueued==="afterHostLayout"&&flushHeadSyncWave()}))}))}function enqueueParentHeadSync(timing,options){let wave=getOrCreatePendingWave(timing);if(options.broadcast)wave.broadcast=!0;else{if(getHeadSyncScheduler(options.childWindow).disposed)return;wave.targets.add(options.childWindow),options.onComplete&&wave.onComplete.set(options.childWindow,options.onComplete)}queuePendingWaveFlush(wave.timing)}function addParentHeadSyncTarget(childWindow){let scheduler=getHeadSyncScheduler(childWindow);scheduler.disposed=!1,activeTargets.add(childWindow),installParentHeadSyncRegistry();let unregistered=!1;return()=>{unregistered||(unregistered=!0,activeTargets.delete(childWindow),teardownParentHeadSyncRegistryIfEmpty())}}function registerParentHeadSyncTarget(childWindow){let unregister=addParentHeadSyncTarget(childWindow);return scheduleSyncParentHeadToChild(childWindow),unregister}function scheduleSyncParentHeadToChild(childWindow,timing="immediate",onComplete){enqueueParentHeadSync(timing,{broadcast:!1,childWindow,onComplete:timing==="afterHostLayout"?onComplete:void 0})}function disposeSyncParentHeadToChild(childWindow){let scheduler=headSyncSchedulers.get(childWindow);scheduler&&(scheduler.disposed=!0),activeTargets.delete(childWindow),teardownParentHeadSyncRegistryIfEmpty(),headSyncSchedulers.delete(childWindow)}function useForceUpdate(){let[,setToggle]=useState2(!1);return useCallback5(()=>setToggle(toggle=>!toggle),[])}function getChildWindow(spatializedElement){return spatializedElement?.windowProxy}function useSync2DFrame(spatialId,portalInstanceObject,spatializedContainerObject,spatializedElement){let forceUpdate=useForceUpdate(),childWindow=getChildWindow(spatializedElement),sync=useCallback5(()=>{if(portalInstanceObject.notify2DFrameChange(),childWindow){scheduleSyncParentHeadToChild(childWindow,"afterHostLayout",()=>{forceUpdate()});return}forceUpdate()},[portalInstanceObject,childWindow,forceUpdate]);useEffect4(()=>(spatializedContainerObject.on2DFrameChange(spatialId,sync),sync(),()=>{spatializedContainerObject.off2DFrameChange(spatialId)}),[spatialId,portalInstanceObject,spatializedContainerObject,sync]),useLayoutEffect2(()=>{if(spatializedElement){if(portalInstanceObject.notify2DFrameChange(),childWindow){scheduleSyncParentHeadToChild(childWindow,"afterHostLayout",()=>{forceUpdate()});return}forceUpdate()}},[spatializedElement,childWindow,portalInstanceObject,forceUpdate])}import{useEffect as useEffect5,useRef as useRef3,useState as useState3}from"react";function useSpatializedElement(createSpatializedElement2,portalInstanceObject){let[spatializedElement,setSpatializedElement]=useState3(),elementRef=useRef3(void 0);return useEffect5(()=>{let cancelled=!1;return createSpatializedElement2().then(inSpatializedElement=>{if(!inSpatializedElement)return;if(cancelled){inSpatializedElement.destroy();return}let previous=elementRef.current;previous&&previous!==inSpatializedElement&&previous.destroy(),elementRef.current=inSpatializedElement,portalInstanceObject.attachSpatializedElement(inSpatializedElement),setSpatializedElement(inSpatializedElement)}),()=>{cancelled=!0}},[createSpatializedElement2,portalInstanceObject]),useEffect5(()=>()=>{let el=elementRef.current;el&&(el.destroy(),elementRef.current=void 0,setSpatializedElement(void 0))},[portalInstanceObject]),spatializedElement}import{useEffect as useEffect6}from"react";function isSupportedSpatializedMotionElement(element){switch(element.kind){case"spatialized2d":case"static3d":case"dynamic3d":return!0;default:return!1}}function useBindSpatializedMotion({binding,element}){useEffect6(()=>{if(!(!binding||!element)&&isSupportedSpatializedMotionElement(element))return binding.__setElement?.(element),()=>{binding.__onUnbind?.(element)}},[binding,element])}import{Fragment,jsx as jsx2,jsxs}from"react/jsx-runtime";function constrainedAxisToVec3(input){if(input==null)return{x:0,y:0,z:0};if(Array.isArray(input))return{x:input[0]??0,y:input[1]??0,z:input[2]??0};let v=input;return{x:v.x,y:v.y,z:v.z}}function constrainedAxisKey(input){let v=constrainedAxisToVec3(input);return`${v.x},${v.y},${v.z}`}function renderPlaceholderInSubPortal(portalInstanceObject,El){let spatialId=portalInstanceObject.spatialId,inPortalInstanceEnv=!!portalInstanceObject.parentPortalInstanceObject,position=portalInstanceObject.computedStyle?.getPropertyValue("position");if(!(inPortalInstanceEnv&&portalInstanceObject&&portalInstanceObject.domRect&&position!=="absolute"&&position!=="fixed"))return jsx2(Fragment,{});let{width,height}=portalInstanceObject.domRect,display=portalInstanceObject.computedStyle.getPropertyValue("display"),spatialIdProps={[SpatialID]:spatialId};return jsx2(El,{...spatialIdProps,style:{position:"relative",width:`${width}px`,height:`${height}px`,visibility:"hidden",display}})}function PortalSpatializedContainer(props){let{spatializedContent:Content,createSpatializedElement:createSpatializedElement2,getExtraSpatializedElementProperties:getExtraSpatializedElementProperties2,"xr-animation":xrAnimation,onSpatialTap,onSpatialDragStart,onSpatialDrag,onSpatialDragEnd,onSpatialRotate,onSpatialRotateEnd,onSpatialMagnify,onSpatialMagnifyEnd,spatialEventOptions,[SpatialID]:spatialId,...restProps}=props,spatializedContainerObject=useContext4(SpatializedContainerContext),parentPortalInstanceObject=useContext4(PortalInstanceContext),portalInstanceObject=useMemo(()=>new PortalInstanceObject(spatialId,spatializedContainerObject,parentPortalInstanceObject,getExtraSpatializedElementProperties2),[]);useEffect7(()=>(portalInstanceObject.init(),()=>{portalInstanceObject.destroy()}),[]);let spatializedElement=useSpatializedElement(createSpatializedElement2,portalInstanceObject);useSync2DFrame(spatialId,portalInstanceObject,spatializedContainerObject,spatializedElement),useBindSpatializedMotion({binding:xrAnimation,element:spatializedElement});let PlaceholderEl=renderPlaceholderInSubPortal(portalInstanceObject,props.component);useEffect7(()=>{spatializedElement&&(spatializedElement.onSpatialTap=onSpatialTap)},[spatializedElement,onSpatialTap]),useEffect7(()=>{spatializedElement&&(spatializedElement.onSpatialDrag=onSpatialDrag)},[spatializedElement,onSpatialDrag]),useEffect7(()=>{spatializedElement&&(spatializedElement.onSpatialDragEnd=onSpatialDragEnd)},[spatializedElement,onSpatialDragEnd]),useEffect7(()=>{spatializedElement&&(spatializedElement.onSpatialRotate=onSpatialRotate)},[spatializedElement,onSpatialRotate]),useEffect7(()=>{spatializedElement&&(spatializedElement.onSpatialRotateEnd=onSpatialRotateEnd)},[spatializedElement,onSpatialRotateEnd]),useEffect7(()=>{spatializedElement&&(spatializedElement.onSpatialMagnify=onSpatialMagnify)},[spatializedElement,onSpatialMagnify]),useEffect7(()=>{spatializedElement&&(spatializedElement.onSpatialMagnifyEnd=onSpatialMagnifyEnd)},[spatializedElement,onSpatialMagnifyEnd]),useEffect7(()=>{spatializedElement&&(spatializedElement.onSpatialDragStart=onSpatialDragStart)},[spatializedElement,onSpatialDragStart]);let rotateConstraintKey=constrainedAxisKey(spatialEventOptions?.constrainedToAxis);return useEffect7(()=>{if(!spatializedElement)return;let axis=constrainedAxisToVec3(spatialEventOptions?.constrainedToAxis);spatializedElement.updateProperties({rotateConstrainedToAxis:axis})},[spatializedElement,rotateConstraintKey]),jsxs(PortalInstanceContext.Provider,{value:portalInstanceObject,children:[spatializedElement&&jsx2(Content,{spatializedElement,portalInstanceObject,...restProps}),PlaceholderEl]})}import{useCallback as useCallback6,useEffect as useEffect8,useRef as useRef4}from"react";import{supports}from"@webspatial/core-sdk";var SpatialContainerRefProxy=class{transformVisibilityTaskContainerDom=null;standardRawDom=null;standardClassObserver=null;mirrorClassNotify=null;lastMirroredClassName=null;classSyncMicrotaskQueued=!1;ref;domProxy;lastOutgoingToRef=void 0;installedProperties=[];extraRefProps;constructor(ref,extraRefProps){this.ref=ref,this.extraRefProps=extraRefProps}setMirrorClassNotify(fn){this.mirrorClassNotify=fn,fn&&this.standardRawDom&&this.flushSyncTransformClassFromStandard(!0)}disconnectStandardClassObserver(){this.standardClassObserver?.disconnect(),this.standardClassObserver=null}attachStandardClassObserver(){this.disconnectStandardClassObserver(),this.standardRawDom&&(this.standardClassObserver=new MutationObserver(()=>{this.ensureSpatialDefaultClass(),this.scheduleSyncTransformClassFromStandard()}),this.standardClassObserver.observe(this.standardRawDom,{attributes:!0,attributeFilter:["class"]}))}ensureSpatialDefaultClass(){let dom=this.standardRawDom;dom&&(dom.classList.contains("xr-spatial-default")||dom.classList.add("xr-spatial-default"))}scheduleSyncTransformClassFromStandard(){this.classSyncMicrotaskQueued||(this.classSyncMicrotaskQueued=!0,queueMicrotask(()=>{this.classSyncMicrotaskQueued=!1,this.flushSyncTransformClassFromStandard(!1)}))}flushSyncTransformClassFromStandard(force){if(!this.standardRawDom)return;let name=this.standardRawDom.className,probe=this.transformVisibilityTaskContainerDom;!force&&probe&&probe.className===name&&this.lastMirroredClassName===name||(this.lastMirroredClassName=name,probe&&(probe.className=name),this.mirrorClassNotify?.(name))}updateStandardSpatializedContainerDom(dom){if(!dom){this.disconnectStandardClassObserver(),this.clearInstalledProperties(),this.standardRawDom=null,this.lastMirroredClassName=null,this.domProxy=void 0,this.updateDomProxyToRef();return}if(this.standardRawDom===dom&&this.domProxy){this.scheduleSyncTransformClassFromStandard();return}this.clearInstalledProperties(),this.standardRawDom=dom,this.domProxy=dom,this.installSpatialRefBehavior(dom);let root=dom.getRootNode();(root===document||root instanceof ShadowRoot)&&ensureSpatialDefaultStyleInRoot(root),this.attachStandardClassObserver(),this.updateDomProxyToRef(),this.scheduleSyncTransformClassFromStandard()}clearInstalledProperties(){let dom=this.standardRawDom;if(dom){for(let prop of this.installedProperties)delete dom[prop];this.installedProperties=[]}}defineDomProperty(dom,prop,descriptor){Object.defineProperty(dom,prop,{configurable:!0,...descriptor}),this.installedProperties.push(prop)}installSpatialRefBehavior(dom){let self=this,rawStyle=dom.style,rawRemoveProperty=rawStyle.removeProperty.bind(rawStyle),rawGetPropertyValue=rawStyle.getPropertyValue.bind(rawStyle),rawRemoveAttribute=dom.removeAttribute.bind(dom),spatialStyleProperties=["visibility","transform"],styleProxy=new Proxy(rawStyle,{get(target,prop){if(prop==="visibility"||prop==="transform")return self.transformVisibilityTaskContainerDom?.style.getPropertyValue(prop);let value=Reflect.get(target,prop);return typeof value=="function"?prop==="setProperty"||prop==="removeProperty"||prop==="getPropertyValue"?function(...args){let[property]=args;if(spatialStyleProperties.includes(property)){if(prop==="setProperty"){let[,kValue,priority]=args;self.transformVisibilityTaskContainerDom?.style.setProperty(property,kValue,priority)}else{if(prop==="removeProperty")return self.transformVisibilityTaskContainerDom?.style.removeProperty(property);if(prop==="getPropertyValue")return self.transformVisibilityTaskContainerDom?.style.getPropertyValue(property)}return}return value.apply(this,args)}.bind(target):value.bind(target):value},set(target,prop,value){if(prop==="visibility")return self.transformVisibilityTaskContainerDom?.style.setProperty("visibility",value),!0;if(prop==="transform")return self.transformVisibilityTaskContainerDom?.style.setProperty("transform",value),!0;if(Object.values(SpatialCustomStyleVars).includes(prop))return target.setProperty(prop,value),!0;if(prop==="cssText"){let{extractedValues,filteredCssText}=extractAndRemoveCustomProperties(value,spatialStyleProperties);spatialStyleProperties.forEach(key=>{extractedValues[key]?self.transformVisibilityTaskContainerDom?.style.setProperty(key,extractedValues[key]):rawRemoveProperty(key)});let appendedCSSText=joinToCSSText({transform:"none",visibility:"hidden"});return Reflect.set(target,prop,[appendedCSSText,filteredCssText].join(";"))}return Reflect.set(target,prop,value)}});if(this.defineDomProperty(dom,"style",{get(){return styleProxy},set(value){styleProxy.cssText=String(value)}}),this.defineDomProperty(dom,"className",{get(){return dom.getAttribute("class")??""},set(value){dom.setAttribute("class",String(value)),dom.classList.contains("xr-spatial-default")||dom.classList.add("xr-spatial-default"),self.scheduleSyncTransformClassFromStandard()}}),this.defineDomProperty(dom,"removeAttribute",{value(property){if(property==="style"){rawStyle.cssText="visibility: hidden; transition: none; transform: none;",self.transformVisibilityTaskContainerDom?.style.removeProperty("visibility"),self.transformVisibilityTaskContainerDom?.style.removeProperty("transform");return}if(property==="class"){dom.className="xr-spatial-default";return}return rawRemoveAttribute(property)}}),supports("xrClientDepth")&&this.defineDomProperty(dom,"xrClientDepth",{get(){return rawGetPropertyValue(SpatialCustomStyleVars.depth)}}),supports("xrOffsetBack")&&this.defineDomProperty(dom,"xrOffsetBack",{get(){return rawGetPropertyValue(SpatialCustomStyleVars.back)}}),this.extraRefProps){let extraProps=this.extraRefProps(dom);for(let prop of Object.keys(extraProps))this.defineDomProperty(dom,prop,{get(){return extraProps[prop]},set(value){extraProps[prop]=value}})}}updateTransformVisibilityTaskContainerDom(dom){this.transformVisibilityTaskContainerDom=dom,dom||(this.lastMirroredClassName=null),this.scheduleSyncTransformClassFromStandard(),this.updateDomProxyToRef()}updateDomProxyToRef(){let ref=this.ref;if(!ref)return;let next=this.domProxy&&this.transformVisibilityTaskContainerDom?this.domProxy:null;this.lastOutgoingToRef!==next&&(this.lastOutgoingToRef=next,next?typeof ref=="function"?ref(next):ref.current=next:typeof ref=="function"?ref(null):ref.current=null)}updateRef(ref){this.ref!==ref&&(this.ref=ref,this.lastOutgoingToRef=void 0,this.updateDomProxyToRef())}};function useDomProxy(ref,extraRefProps){let spatialContainerRefProxy=useRef4(new SpatialContainerRefProxy(ref,extraRefProps));useEffect8(()=>{spatialContainerRefProxy.current.updateRef(ref)},[ref]);let transformVisibilityTaskContainerCallback=useCallback6(el=>{spatialContainerRefProxy.current.updateTransformVisibilityTaskContainerDom(el)},[]),standardSpatializedContainerCallback=useCallback6(el=>{spatialContainerRefProxy.current.updateStandardSpatializedContainerDom(el)},[]);return{transformVisibilityTaskContainerCallback,standardSpatializedContainerCallback,spatialContainerRefProxy}}import{createContext as createContext4,useContext as useContext5}from"react";var InsideAttachmentContext=createContext4(!1),useInsideAttachment=()=>useContext5(InsideAttachmentContext);function createEventProxy(event,currentTargetGetter,offsetXGetter,offsetYGetter,offsetZGetter,clientXGetter,clientYGetter,clientZGetter,translationXGetter,translationYGetter,translationZGetter,quaternionGetter,magnificationGetter){return new Proxy(event,{get(target,prop){return prop==="currentTarget"?currentTargetGetter():prop==="isTrusted"?!0:prop==="bubbles"?!1:prop==="offsetX"&&offsetXGetter?offsetXGetter(target)??0:prop==="offsetY"&&offsetYGetter?offsetYGetter(target)??0:prop==="offsetZ"&&offsetZGetter?offsetZGetter(target)??0:prop==="clientX"&&clientXGetter?clientXGetter(target)??0:prop==="clientY"&&clientYGetter?clientYGetter(target)??0:prop==="clientZ"&&clientZGetter?clientZGetter(target)??0:prop==="translationX"&&translationXGetter?translationXGetter(target)??0:prop==="translationY"&&translationYGetter?translationYGetter(target)??0:prop==="translationZ"&&translationZGetter?translationZGetter(target)??0:prop==="quaternion"&&quaternionGetter?quaternionGetter(target)??{x:0,y:0,z:0,w:1}:prop==="magnification"&&magnificationGetter?magnificationGetter(target)??1:Reflect.get(target,prop)}})}function createEventHandler(handler,currentTargetGetter,offsetXGetter,offsetYGetter,offsetZGetter,clientXGetter,clientYGetter,clientZGetter,translationXGetter,translationYGetter,translationZGetter,quaternionGetter,magnificationGetter){return handler?event=>{let proxyEvent=createEventProxy(event,currentTargetGetter,offsetXGetter,offsetYGetter,offsetZGetter,clientXGetter,clientYGetter,clientZGetter,translationXGetter,translationYGetter,translationZGetter,quaternionGetter,magnificationGetter);handler(proxyEvent)}:void 0}function useSpatialEventsBase(spatialEvents,currentTargetGetter){let onSpatialTap=createEventHandler(spatialEvents.onSpatialTap,currentTargetGetter,ev=>ev.detail?.location3D?.x,ev=>ev.detail?.location3D?.y,ev=>ev.detail?.location3D?.z,ev=>ev.detail?.globalLocation3D?.x,ev=>ev.detail?.globalLocation3D?.y,ev=>ev.detail?.globalLocation3D?.z),onSpatialDrag=createEventHandler(spatialEvents.onSpatialDrag,currentTargetGetter,void 0,void 0,void 0,void 0,void 0,void 0,ev=>ev.detail?.translation3D?.x,ev=>ev.detail?.translation3D?.y,ev=>ev.detail?.translation3D?.z),onSpatialDragEnd=createEventHandler(spatialEvents.onSpatialDragEnd,currentTargetGetter),onSpatialRotate=createEventHandler(spatialEvents.onSpatialRotate,currentTargetGetter,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,ev=>ev.detail?.quaternion),onSpatialRotateEnd=createEventHandler(spatialEvents.onSpatialRotateEnd,currentTargetGetter),onSpatialMagnify=createEventHandler(spatialEvents.onSpatialMagnify,currentTargetGetter,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,ev=>ev.detail?.magnification),onSpatialMagnifyEnd=createEventHandler(spatialEvents.onSpatialMagnifyEnd,currentTargetGetter),onSpatialDragStart=createEventHandler(spatialEvents.onSpatialDragStart,currentTargetGetter,ev=>ev.detail?.startLocation3D?.x,ev=>ev.detail?.startLocation3D?.y,ev=>ev.detail?.startLocation3D?.z,ev=>ev.detail?.globalLocation3D?.x,ev=>ev.detail?.globalLocation3D?.y,ev=>ev.detail?.globalLocation3D?.z);return{onSpatialTap,onSpatialDragStart,onSpatialDrag,onSpatialDragEnd,onSpatialRotate,onSpatialRotateEnd,onSpatialMagnify,onSpatialMagnifyEnd}}function useSpatialEvents(spatialEvents,spatialContainerRefProxy){return useSpatialEventsBase(spatialEvents,()=>spatialContainerRefProxy.current?.domProxy)}function useSpatialEventsWhenSpatializedContainerExist(spatialEvents,spatialId,spatializedContainerObject){return useSpatialEventsBase(spatialEvents,()=>spatializedContainerObject.getSpatialContainerRefProxyBySpatialId(spatialId)?.domProxy)}import{jsx as jsx3,jsxs as jsxs2}from"react/jsx-runtime";function DegradedContainer({innerRef,...inprops}){let{component:Component,children,["enable-xr"]:_enableXR,onSpatialTap:_onSpatialTap,onSpatialDragStart:_onSpatialDragStart,onSpatialDrag:_onSpatialDrag,onSpatialDragEnd:_onSpatialDragEnd,onSpatialRotate:_onSpatialRotate,onSpatialRotateEnd:_onSpatialRotateEnd,onSpatialMagnify:_onSpatialMagnify,onSpatialMagnifyEnd:_onSpatialMagnifyEnd,spatialEventOptions:_spatialEventOptions,spatializedContent:_content,createSpatializedElement:_create,getExtraSpatializedElementProperties:_getExtra,extraRefProps:_extraRef,sizingMode:_sizingMode,onSpatialContentReady:_onSpatialContentReady,"xr-animation":xrAnimation,...restProps}=inprops;return jsx3(Component,{ref:innerRef,...restProps,children})}function SpatializedContainerBase(inprops,ref){let isWebSpatialEnv=getSession()!==null,insideAttachment=useInsideAttachment();if(!isWebSpatialEnv||insideAttachment)return insideAttachment&&console.warn(`[WebSpatial] ${inprops.component||"Spatial element"} cannot be used inside AttachmentAsset. Rendering as plain HTML.`),jsx3(DegradedContainer,{...inprops,innerRef:ref});let layer=useContext6(SpatialLayerContext)+1,rootSpatializedContainerObject=useContext6(SpatializedContainerContext),inSpatializedContainer=!!rootSpatializedContainerObject,inPortalInstanceEnv=!!useContext6(PortalInstanceContext),isInStandardInstance=!inPortalInstanceEnv,spatialId=useMemo2(()=>inSpatializedContainer?rootSpatializedContainerObject.getSpatialId(layer,isInStandardInstance):"root_container",[]),spatialIdProps={[SpatialID]:spatialId},{onSpatialTap,onSpatialDragStart,onSpatialDrag,onSpatialDragEnd,onSpatialRotate,onSpatialRotateEnd,onSpatialMagnify,onSpatialMagnifyEnd,extraRefProps,...props}=inprops;if(inSpatializedContainer)if(inPortalInstanceEnv){let spatialEvents=useSpatialEventsWhenSpatializedContainerExist({onSpatialTap,onSpatialDragStart,onSpatialDrag,onSpatialDragEnd,onSpatialRotate,onSpatialRotateEnd,onSpatialMagnify,onSpatialMagnifyEnd},spatialId,rootSpatializedContainerObject);return jsx3(SpatialLayerContext.Provider,{value:layer,children:jsx3(PortalSpatializedContainer,{...spatialIdProps,...props,...spatialEvents})})}else{let{transformVisibilityTaskContainerCallback,standardSpatializedContainerCallback,spatialContainerRefProxy}=useDomProxy(ref,extraRefProps),[probeClassName,setProbeClassName]=useState4(()=>props.className??""),notifyProbeClass=useCallback7(name=>{setProbeClassName(prev=>prev===name?prev:name)},[]);useEffect9(()=>(spatialContainerRefProxy.current.setMirrorClassNotify?.(notifyProbeClass),()=>{spatialContainerRefProxy.current.setMirrorClassNotify?.(null)}),[spatialContainerRefProxy,notifyProbeClass]),useEffect9(()=>{rootSpatializedContainerObject.updateSpatialContainerRefProxyInfo(spatialId,spatialContainerRefProxy.current)},[spatialContainerRefProxy.current]);let{spatializedContent,createSpatializedElement:createSpatializedElement2,getExtraSpatializedElementProperties:getExtraSpatializedElementProperties2,"xr-animation":_xrAnimation,spatialEventOptions:_nestedSpatialEventOptions,onSpatialContentReady:_nestedOnSpatialContentReady,...restProps}=props;return jsxs2(SpatialLayerContext.Provider,{value:layer,children:[jsx3(StandardSpatializedContainer,{ref:standardSpatializedContainerCallback,...spatialIdProps,...restProps,inStandardSpatializedContainer:!0}),jsx3(TransformVisibilityTaskContainer,{ref:transformVisibilityTaskContainerCallback,...spatialIdProps,component:props.component,className:probeClassName,style:props.style})]})}else{let{transformVisibilityTaskContainerCallback,standardSpatializedContainerCallback,spatialContainerRefProxy}=useDomProxy(ref,extraRefProps),[probeClassName,setProbeClassName]=useState4(()=>props.className??""),notifyProbeClass=useCallback7(name=>{setProbeClassName(prev=>prev===name?prev:name)},[]);useEffect9(()=>(spatialContainerRefProxy.current.setMirrorClassNotify?.(notifyProbeClass),()=>{spatialContainerRefProxy.current.setMirrorClassNotify?.(null)}),[spatialContainerRefProxy,notifyProbeClass]);let spatialEvents=useSpatialEvents({onSpatialTap,onSpatialDragStart,onSpatialDrag,onSpatialDragEnd,onSpatialRotate,onSpatialRotateEnd,onSpatialMagnify,onSpatialMagnifyEnd},spatialContainerRefProxy),spatializedContainerObject=useMemo2(()=>new SpatializedContainerObject,[]),{spatializedContent,createSpatializedElement:createSpatializedElement2,getExtraSpatializedElementProperties:getExtraSpatializedElementProperties2,"xr-animation":_xrAnimation,spatialEventOptions:_rootSpatialEventOptions,onSpatialContentReady:_rootOnSpatialContentReady,...restProps}=props;return jsx3(SpatialLayerContext.Provider,{value:layer,children:jsxs2(SpatializedContainerContext.Provider,{value:spatializedContainerObject,children:[jsx3(StandardSpatializedContainer,{ref:standardSpatializedContainerCallback,...spatialIdProps,...restProps,inStandardSpatializedContainer:!1}),jsx3(PortalSpatializedContainer,{...spatialIdProps,...props,...spatialEvents}),jsx3(TransformVisibilityTaskContainer,{ref:transformVisibilityTaskContainerCallback,...spatialIdProps,component:props.component,className:probeClassName,style:props.style})]})})}}var SpatializedContainer=forwardRef3(SpatializedContainerBase);import{createPortal as createPortal2}from"react-dom";import{forwardRef as forwardRef4,useCallback as useCallback8,useEffect as useEffect11,useState as useState5}from"react";import{useEffect as useEffect10}from"react";function useSyncHeadStyles(childWindow){useEffect10(()=>{if(!childWindow)return;let unregister=registerParentHeadSyncTarget(childWindow);return()=>{unregister(),disposeSyncParentHeadToChild(childWindow)}},[childWindow])}import{useLayoutEffect as useLayoutEffect3,useRef as useRef5}from"react";var isDev=process.env.NODE_ENV!=="production";function safeInvokeCleanup(cleanup){if(cleanup)try{cleanup()}catch(e){isDev&&console.error("[WebSpatial] onSpatialContentReady cleanup threw",e)}}function useSpatialContentReady(params){let{spatializedElement,portalInstanceObject,hostElement,onSpatialContentReady}=params,callbackRef=useRef5(onSpatialContentReady);callbackRef.current=onSpatialContentReady;let portalDom=portalInstanceObject?.dom;useLayoutEffect3(()=>{if(!!!(spatializedElement&&portalDom&&hostElement&&hostElement.isConnected)||!hostElement)return()=>{};let cb=callbackRef.current,cleanupFromCallback;if(cb)try{let ret=cb({host:hostElement});cleanupFromCallback=typeof ret=="function"?ret:void 0}catch(e){isDev&&console.error("[WebSpatial] onSpatialContentReady threw",e)}return()=>{safeInvokeCleanup(cleanupFromCallback)}},[spatializedElement,portalDom,hostElement])}import{jsx as jsx4}from"react/jsx-runtime";function mergeRefs(...refs){return value=>{for(let ref of refs)ref!=null&&(typeof ref=="function"?ref(value):ref.current=value)}}function getJSXPortalInstance(inProps,portalInstanceObject,hostRef){let{component:El,style:inStyle={},ref:userRef,...props}=inProps,extraStyle={visibility:"visible",position:"relative",top:"0px",left:"0px",margin:"0px",marginLeft:"0px",marginRight:"0px",marginTop:"0px",marginBottom:"0px",borderRadius:"0px",...detectSpatialRuntime()==="visionos"?{opacity:1}:{},transform:"none"},computedStyle=portalInstanceObject.computedStyle,inheritedPortalStyle=computedStyle?getInheritedStyleProps(computedStyle):{},style={...inStyle,...inheritedPortalStyle,...extraStyle},mergedRef=hostRef!=null?mergeRefs(hostRef,userRef):userRef;return jsx4(El,{ref:mergedRef,style,...props})}function useSyncDocumentTitle(windowProxy,spatializedElement,name){useEffect11(()=>{windowProxy.document.title=name,spatializedElement.updateProperties({name})},[name])}function SpatializedContent(props){let{spatializedElement,portalInstanceObject,onSpatialContentReady,...restProps}=props,spatialized2DElement=spatializedElement,{windowProxy}=spatialized2DElement,[hostEl,setHostEl]=useState5(null);useSpatialContentReady({spatializedElement,portalInstanceObject,hostElement:hostEl,onSpatialContentReady}),useSyncHeadStyles(windowProxy);let name=restProps["data-name"]||"";useSyncDocumentTitle(windowProxy,spatialized2DElement,name);let setHostCallback=useCallback8(el=>{setHostEl(el)},[]),JSXPortalInstance=getJSXPortalInstance(restProps,portalInstanceObject,setHostCallback);return createPortal2(JSXPortalInstance,windowProxy.document.body)}function getExtraSpatializedElementProperties(computedStyle){let overflow=computedStyle.getPropertyValue("overflow"),scrollPageEnabled=["visible","hidden","clip"].indexOf(overflow)>=0,material=computedStyle.getPropertyValue(SpatialCustomStyleVars.backgroundMaterial),properties={};return properties.scrollPageEnabled=scrollPageEnabled,properties.cornerRadius=parseCornerRadius(computedStyle),material&&(properties.material=material),properties}async function createSpatializedElement(){let spatializedElement=await getSession().createSpatialized2DElement(),{windowProxy}=spatializedElement;setOpenWindowStyle(windowProxy),await syncParentHeadToChild(windowProxy);let viewport=windowProxy.document.querySelector('meta[name="viewport"]');if(viewport)viewport?.setAttribute("content"," initial-scale=1.0, maximum-scale=1.0, user-scalable=no");else{let meta=windowProxy.document.createElement("meta");meta.name="viewport",meta.content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no",windowProxy.document.head.appendChild(meta)}return spatializedElement}function Spatialized2DElementContainerBase(props,ref){return jsx4(SpatializedContainer,{ref,createSpatializedElement,getExtraSpatializedElementProperties,spatializedContent:SpatializedContent,...props})}var Spatialized2DElementContainer=forwardRef4(Spatialized2DElementContainerBase);import{Children,forwardRef as forwardRef5,isValidElement,useCallback as useCallback9,useContext as useContext7,useEffect as useEffect12,useMemo as useMemo3,useRef as useRef6}from"react";import{Fragment as Fragment2,jsx as jsx5}from"react/jsx-runtime";function getAbsoluteURL(url){if(!url)return url;try{return new URL(url,document.baseURI).toString()}catch{return url}}function createLoadEvent(type,targetGetter){let event=new CustomEvent(type,{bubbles:!1,cancelable:!1});return new Proxy(event,{get(target,prop){return prop==="target"||prop==="currentTarget"?targetGetter():Reflect.get(target,prop)}})}function createLoadFailureEvent(targetGetter){return createLoadEvent("modelloadfailed",targetGetter)}function createLoadSuccessEvent(targetGetter){return createLoadEvent("modelloaded",targetGetter)}function collectSources(children){let sources=[];return Children.forEach(children,child=>{if(isValidElement(child)&&child.type==="source"){let{src,type}=child.props;src&&sources.push({src:getAbsoluteURL(src),type})}}),sources}function getDomSpatializedStaticElement(domProxy){let proxy=domProxy;return proxy.__spatializedElement??proxy.__innerSpatializedElement?.()}function SpatializedContent2(props){let{src,poster,children,spatializedElement,onLoad,onError,autoPlay,loop,loading="eager",stagemode="none"}=props,portalInstanceObject=useContext7(PortalInstanceContext),wasVisible=useRef6(!1),modelURL=useMemo3(()=>getAbsoluteURL(src),[src]),posterURL=useMemo3(()=>getAbsoluteURL(poster),[poster]),sources=useMemo3(()=>collectSources(children),[children]),sourcesKey=useMemo3(()=>JSON.stringify(sources),[sources]);return useEffect12(()=>{let target=portalInstanceObject?.dom;if(wasVisible.current=!1,loading!=="lazy"){wasVisible.current=!0;return}if(!target)return;if(typeof IntersectionObserver>"u"){wasVisible.current=!0,spatializedElement.updateProperties({loading:"eager"});return}let observer=new IntersectionObserver(entries=>{entries.some(entry=>entry.isIntersecting)&&(wasVisible.current=!0,observer.disconnect(),spatializedElement.updateProperties({loading:"eager"}))});return observer.observe(target),()=>observer.disconnect()},[modelURL,sourcesKey,portalInstanceObject?.dom]),useEffect12(()=>{loading!=="lazy"&&(wasVisible.current=!0),spatializedElement.updateProperties({modelURL:modelURL??(spatializedElement.modelUrl?"":modelURL),sources,autoplay:autoPlay,loop,posterURL:posterURL??"",loading:loading==="lazy"&&wasVisible.current?"eager":loading,stagemode})},[modelURL,sourcesKey,autoPlay,loop,posterURL,loading,stagemode]),useEffect12(()=>{let dom=portalInstanceObject?.dom;onLoad&&dom?spatializedElement.onLoadCallback=()=>{onLoad(createLoadSuccessEvent(()=>dom))}:spatializedElement.onLoadCallback=void 0},[onLoad,portalInstanceObject?.dom]),useEffect12(()=>{let dom=portalInstanceObject?.dom;onError&&dom?spatializedElement.onLoadFailureCallback=()=>{onError(createLoadFailureEvent(()=>dom))}:spatializedElement.onLoadFailureCallback=void 0},[onError,portalInstanceObject?.dom]),jsx5(Fragment2,{})}function SpatializedStatic3DElementContainerBase(props,ref){let promiseRef=useRef6(null),createSpatializedElement2=useCallback9(()=>(promiseRef.current=getSession().createSpatializedStatic3DElement(getAbsoluteURL(props.src),collectSources(props.children),props.loading==="lazy"?"lazy":"eager"),promiseRef.current),[]),extraRefProps=useCallback9(domProxy=>({get currentSrc(){return getDomSpatializedStaticElement(domProxy)?.currentSrc??""},get ready(){let spatializedElement=getDomSpatializedStaticElement(domProxy),readySource=spatializedElement?Promise.resolve(spatializedElement):promiseRef.current;return readySource?readySource.then(element=>element.ready).then(success=>{if(success)return createLoadSuccessEvent(()=>domProxy);throw createLoadFailureEvent(()=>domProxy)}):Promise.reject(createLoadFailureEvent(()=>domProxy))},get entityTransform(){return getDomSpatializedStaticElement(domProxy)?.entityTransform??new DOMMatrixReadOnly},set entityTransform(value){let spatializedElement=getDomSpatializedStaticElement(domProxy);spatializedElement&&(spatializedElement.entityTransform=value)},async play(){await getDomSpatializedStaticElement(domProxy)?.play()},async pause(){await getDomSpatializedStaticElement(domProxy)?.pause()},get paused(){return getDomSpatializedStaticElement(domProxy)?.paused??!0},get duration(){return getDomSpatializedStaticElement(domProxy)?.duration??0},get playbackRate(){return getDomSpatializedStaticElement(domProxy)?.playbackRate??1},set playbackRate(value){let spatializedElement=getDomSpatializedStaticElement(domProxy);spatializedElement&&(spatializedElement.playbackRate=value)},get currentTime(){return getDomSpatializedStaticElement(domProxy)?.currentTime??0},set currentTime(value){let spatializedElement=getDomSpatializedStaticElement(domProxy);spatializedElement&&(spatializedElement.currentTime=value)}}),[]);return jsx5(SpatializedContainer,{ref,component:"div",createSpatializedElement:createSpatializedElement2,spatializedContent:SpatializedContent2,extraRefProps,...props})}var SpatializedStatic3DElementContainer=forwardRef5(SpatializedStatic3DElementContainerBase);import{forwardRef as forwardRef6}from"react";import{jsx as jsx6}from"react/jsx-runtime";var CachedSpatialized2DElementContainerType=new Map;function withSpatialized2DElementContainer(Component){if(CachedSpatialized2DElementContainerType.has(Component))return CachedSpatialized2DElementContainerType.get(Component);{let TypedSpatialized2DElementContainer=forwardRef6((givenProps,ref)=>{let{component:ignoreComponent,...props}=givenProps;return jsx6(Spatialized2DElementContainer,{component:Component,...props,ref})});return CachedSpatialized2DElementContainerType.set(Component,TypedSpatialized2DElementContainer),CachedSpatialized2DElementContainerType.set(TypedSpatialized2DElementContainer,TypedSpatialized2DElementContainer),TypedSpatialized2DElementContainer}}import{useEffect as useEffect13,useMemo as useMemo4,useReducer,useRef as useRef7}from"react";function getMotionConfigSignature(config){let effectiveConfig=config.timeline!==void 0?{...config,from:void 0,to:void 0}:config;return JSON.stringify(effectiveConfig,(_key,value)=>typeof value=="function"?void 0:value)}import{supports as supports2,validateSpatializedMotionConfig}from"@webspatial/core-sdk";function supportsAnimation(){return supports2("useAnimation")}var AnimationBinding=class{__kind="spatializedMotion";animationObject=null;element=null;destroyed=!1;creating=!1;createToken=0;pendingCommands=[];configSignature;config;values;state="idle";isAnimatingState=!1;isPausedState=!1;finishedState=!1;options;constructor(config,options={}){validateSpatializedMotionConfig(config),this.options=options,this.config=config,this.configSignature=getMotionConfigSignature(config),this.values={}}get configSnapshot(){return this.config}get currentValues(){return this.values}get targetKind(){return this.element?.kind??null}get playState(){return this.animationObject?this.animationObject.playState:this.pendingCommands.length>0?"queued":this.state}get isAnimating(){return this.animationObject?this.animationObject.isAnimating:this.isAnimatingState}get isPaused(){return this.animationObject?this.animationObject.isPaused:this.isPausedState}get finished(){return this.animationObject?this.animationObject.finished:this.finishedState}__setElement(element){this.bind(element)}__onUnbind(element){this.unbind(element)}play(){this.dispatchCommand({type:"play"})}pause(){this.dispatchCommand({type:"pause"})}stop(){this.dispatchCommand({type:"stop"})}reset(){this.dispatchCommand({type:"reset"})}finish(){this.dispatchCommand({type:"finish"})}updateConfig(config){validateSpatializedMotionConfig(config);let nextSignature=getMotionConfigSignature(config),previousConfig=this.config;this.config=config,nextSignature!==this.configSignature?(this.configSignature=nextSignature,this.recreateAnimationObject(previousConfig)):this.animationObject&&this.animationObject.setCallbacks(this.createAnimationObjectCallbacks(this.animationObject))}destroy(){this.destroyed=!0,this.pendingCommands=[],this.detachAnimationObject(),this.element=null,this.options.onStateChange?.()}bind(element){if(!this.destroyed){if(!element){this.unbind();return}if(this.element&&this.element!==element){console.warn("[AnimationBinding] motion binding already attached to another component; ignoring subsequent bind.");return}validateSpatializedMotionConfig(this.config),this.element=element,this.ensureAnimationObject(),this.options.onStateChange?.()}}unbind(element){this.destroyed||element&&this.element!==element||(this.detachAnimationObject(),this.element=null,this.options.onStateChange?.())}detachAnimationObject(config=this.config){let object=this.animationObject,onError=config.onError;this.animationObject=null,this.createToken+=1,this.creating=!1,object?.destroy().catch(error=>{onError?.({command:"destroy",reason:error instanceof Error?error.message:"Destroy failed"})}),this.state="idle",this.isAnimatingState=!1,this.isPausedState=!1,this.finishedState=!1}recreateAnimationObject(detachedConfig=this.config){let element=this.element;if(this.detachAnimationObject(detachedConfig),element&&supportsAnimation()){this.ensureAnimationObject();return}this.values={},this.options.onValuesChange?.(this.values),this.options.onStateChange?.()}ensureAnimationObject(){if(this.animationObject||this.creating||!this.element||!supportsAnimation())return;let token=++this.createToken,element=this.element,kind=element.kind;this.creating=!0,element.createAnimation(this.config).then(async animationObject=>{if(this.destroyed||token!==this.createToken||this.element!==element||this.element.kind!==kind){animationObject.destroy().catch(()=>{});return}this.animationObject=animationObject,this.creating=!1,animationObject.setCallbacks(this.createAnimationObjectCallbacks(animationObject)),this.syncStateFromAnimationObject(),this.config.autoStart!==!1&&this.pendingCommands.unshift({type:"play"}),await this.flushPendingCommands(),!(this.destroyed||token!==this.createToken||this.animationObject!==animationObject||this.element!==element||this.element.kind!==kind)&&this.options.onStateChange?.()}).catch(error=>{token===this.createToken&&(this.creating=!1,this.pendingCommands=[],this.state="idle",this.isAnimatingState=!1,this.isPausedState=!1,this.finishedState=!1,this.config.onError?.({command:"create",reason:error instanceof Error?error.message:"Create failed"}),this.options.onStateChange?.())})}createAnimationObjectCallbacks(animationObject){let isCurrent=()=>!this.destroyed&&this.animationObject===animationObject;return{onStart:()=>{isCurrent()&&this.config.onStart?.()},onComplete:values=>{isCurrent()&&this.config.onComplete?.(values)},onStop:values=>{isCurrent()&&this.config.onStop?.(values)},onReset:values=>{isCurrent()&&this.config.onReset?.(values)},onError:error=>{isCurrent()&&this.config.onError?.(error)},onValuesChange:values=>{isCurrent()&&(this.values=values,this.options.onValuesChange?.(values))},onStateChange:()=>{isCurrent()&&(this.syncStateFromAnimationObject(),this.options.onStateChange?.())}}}syncStateFromAnimationObject(){this.animationObject&&(this.state=this.animationObject.playState,this.isAnimatingState=this.animationObject.isAnimating,this.isPausedState=this.animationObject.isPaused,this.finishedState=this.animationObject.finished)}dispatchCommand(command){if(!this.destroyed){if(!this.animationObject||!this.element){this.pendingCommands.push(command),this.applyQueuedState(command),this.options.onStateChange?.();return}this.animationObject[command.type]().catch(error=>{this.config.onError?.({command:command.type,reason:error instanceof Error?error.message:"Command failed"})}),this.syncStateFromAnimationObject(),this.options.onStateChange?.()}}applyQueuedState(command){switch(command.type){case"play":this.state="queued",this.isAnimatingState=!0,this.isPausedState=!1,this.finishedState=!1;break;case"pause":this.state="queued",this.isAnimatingState=!1,this.isPausedState=!0;break;case"stop":case"reset":case"finish":this.state="queued",this.isAnimatingState=!1,this.isPausedState=!1,this.finishedState=!1;break}}async flushPendingCommands(){if(!this.animationObject||!this.element)return;let animationObject=this.animationObject,commands=this.pendingCommands;this.pendingCommands=[];for(let command of commands){try{await animationObject[command.type]()}catch(error){this.config.onError?.({command:command.type,reason:error instanceof Error?error.message:"Command failed"})}if(this.destroyed||this.animationObject!==animationObject||!this.element)return}this.syncStateFromAnimationObject()}};function valuesToMotionStyle(values){let style={};values.opacity!==void 0&&(style.opacity=values.opacity);let t=values.transform;if(t){let parts=[],tr=t.translate;tr&&(tr.x!==void 0||tr.y!==void 0||tr.z!==void 0)&&parts.push(`translate3d(${tr.x??0}px, ${tr.y??0}px, ${tr.z??0}px)`);let rot=t.rotate;rot&&(rot.z!==void 0&&parts.push(`rotateZ(${rot.z}deg)`),rot.y!==void 0&&parts.push(`rotateY(${rot.y}deg)`),rot.x!==void 0&&parts.push(`rotateX(${rot.x}deg)`));let sc=t.scale;sc&&(sc.x!==void 0&&parts.push(`scaleX(${sc.x})`),sc.y!==void 0&&parts.push(`scaleY(${sc.y})`),sc.z!==void 0&&parts.push(`scaleZ(${sc.z})`)),parts.length>0&&(style.transform=parts.join(" "))}return style}function useAnimation(config){let dataSignature=getMotionConfigSignature(config),[,forceRender]=useReducer(n=>n+1,0),bindingRef=useRef7(null),destroyTimerRef=useRef7(null);bindingRef.current||(bindingRef.current=new AnimationBinding(config,{onValuesChange:()=>forceRender(),onStateChange:()=>forceRender()}));let binding=bindingRef.current;useEffect13(()=>{binding.updateConfig(config)},[binding,config,dataSignature]),useEffect13(()=>(destroyTimerRef.current&&(clearTimeout(destroyTimerRef.current),destroyTimerRef.current=null),()=>{let bindingToDestroy=binding;destroyTimerRef.current=setTimeout(()=>{bindingRef.current===bindingToDestroy&&(bindingToDestroy.destroy(),bindingRef.current=null),destroyTimerRef.current=null},0)}),[binding]);let api=useMemo4(()=>({play:()=>binding.play(),pause:()=>binding.pause(),stop:()=>binding.stop(),reset:()=>binding.reset(),finish:()=>binding.finish(),get isAnimating(){return binding.isAnimating},get isPaused(){return binding.isPaused},get finished(){return binding.finished},get playState(){return binding.playState}}),[binding]),values=binding.currentValues,style=valuesToMotionStyle(values);return[binding,api,style]}function initPolyfill(){injectSpatialDefaultStyle(),initCSSParserDivContainer()}import{forwardRef as forwardRef7}from"react";import{Spatial as Spatial2}from"@webspatial/core-sdk";import{jsx as jsx7}from"react/jsx-runtime";var spatial2=new Spatial2;function ModelBase(props,ref){let insideAttachment=useInsideAttachment(),{"enable-xr":enableXR,...restProps}=props;if(!enableXR||!spatial2.runInSpatialWeb()||insideAttachment){let{onSpatialTap,onSpatialDragStart,onSpatialDrag,onSpatialDragEnd,onSpatialRotate,onSpatialRotateEnd,onSpatialMagnify,onSpatialMagnifyEnd,spatialEventOptions:_spatialEventOptions,"xr-animation":_xrAnimation,...modelProps}=restProps;return jsx7("model",{ref,...modelProps})}if(restProps.stagemode==="orbit"){let{onSpatialTap,onSpatialDragStart,onSpatialDrag,onSpatialDragEnd,onSpatialRotate,onSpatialRotateEnd,onSpatialMagnify,onSpatialMagnifyEnd,...orbitProps}=restProps;return jsx7(SpatializedStatic3DElementContainer,{ref,...orbitProps})}return jsx7(SpatializedStatic3DElementContainer,{ref,...restProps})}var Model=forwardRef7(ModelBase);Model.displayName="Model";markWebSpatialPrimitive(Model,"Model");import{forwardRef as forwardRef9}from"react";import{forwardRef as forwardRef8}from"react";import{createContext as createContext5,useContext as useContext8}from"react";var RealityContext=createContext5(null),useRealityContext=()=>useContext8(RealityContext);import{createContext as createContext6,useContext as useContext9}from"react";var ParentContext=createContext6(null),useParentContext=()=>useContext9(ParentContext);import{createContext as createContext7,useContext as useContext10}from"react";var AttachmentRegistry=class{containers=new Map;listeners=new Map;addContainer(name,instanceId,container){this.containers.has(name)||this.containers.set(name,new Map),this.containers.get(name).set(instanceId,container),this.notifyListeners(name)}removeContainer(name,instanceId){this.containers.get(name)?.delete(instanceId),this.containers.get(name)?.size===0&&this.containers.delete(name),this.notifyListeners(name)}getContainers(name){let map=this.containers.get(name);return map?Array.from(map,([instanceId,container])=>({instanceId,container})):[]}onContainersChange(name,cb){let current=this.getContainers(name);current.length>0&&cb(current);let prev=this.listeners.get(name);return prev&&prev([]),this.listeners.set(name,cb),()=>{this.listeners.get(name)===cb&&this.listeners.delete(name)}}notifyListeners(name){let cs=this.getContainers(name);this.listeners.get(name)?.(cs)}destroy(){this.containers.clear(),this.listeners.clear()}},AttachmentContext=createContext7(null);import{useEffect as useEffect14,useRef as useRef8}from"react";var ResourceRegistry=class{resources=new Map;registered=new Set;deferreds=new Map;listeners=new Map;add(id,resource){this.registered.add(id),this.resources.set(id,resource);let deferred=this.deferreds.get(id);deferred&&(resource.then(deferred.resolve).catch(err=>deferred.reject(err instanceof Error?err:new Error(String(err)))),this.deferreds.delete(id)),resource.then(()=>this.notify(id)).catch(()=>this.notify(id))}subscribe(id,listener){let listeners=this.listeners.get(id)??new Set;return listeners.add(listener),this.listeners.set(id,listeners),()=>{listeners.delete(listener),listeners.size===0&&this.listeners.delete(id)}}notify(id){let listeners=this.listeners.get(id);if(listeners)for(let listener of Array.from(listeners))listener()}has(id){return this.registered.has(id)}get(id){let existing=this.resources.get(id);if(existing)return existing;let promise=new Promise((resolve,reject)=>{this.deferreds.set(id,{resolve,reject})});return this.resources.set(id,promise),promise}remove(id){this.registered.delete(id),this.resources.delete(id),this.deferreds.delete(id),this.notify(id)}removeAndDestroy(id){let p=this.resources.get(id);p&&p.then(obj=>obj.destroy()).catch(()=>{}),this.registered.delete(id),this.resources.delete(id),this.deferreds.delete(id),this.notify(id)}destroy(){for(let[id,deferred]of this.deferreds)deferred.reject(new Error(`ResourceRegistry destroyed \u2014 "${id}" never resolved`));this.deferreds.clear();let ids=Array.from(this.resources.keys());for(let id of ids)this.notify(id);this.listeners.clear(),this.registered.clear();let pending=Array.from(this.resources.values());this.resources.clear(),Promise.allSettled(pending.map(p=>p.then(obj=>obj.destroy())))}};function shallowEqualVec3(a,b){return a===b?!0:!a||!b?!1:a.x===b.x&&a.y===b.y&&a.z===b.z}function shallowEqualRotation(a,b){return a===b?!0:!a||!b?!1:a.x===b.x&&a.y===b.y&&a.z===b.z&&("w"in a?a.w===b.w:!0)}function shallowEqualObject(a,b){if(a===b)return!0;if(!a||!b)return!1;let keysA=Object.keys(a),keysB=Object.keys(b);return keysA.length!==keysB.length?!1:keysA.every(key=>a[key]===b[key])}function shallowEqualArray(a,b){return a===b?!0:!a||!b||a.length!==b.length?!1:a.every((val,i)=>val===b[i])}var AbortResourceManager=class{resources=[];aborted=!1;constructor(signal){signal.addEventListener("abort",()=>{this.aborted=!0,this.dispose()})}async addResource(factory){if(this.aborted)throw new DOMException("Aborted","AbortError");let resource=await factory();if(this.aborted)throw await resource.destroy(),new DOMException("Aborted","AbortError");return this.resources.push(resource),resource}async dispose(){let resources=this.resources.splice(0);for(let r of resources)try{await r.destroy()}catch(e){console.error("AbortResourceManager dispose error:",e,r)}}};function useEntityTransform(entity,{position,rotation,scale,animation}){let last=useRef8({}),isAnimating=animation?animation.__animating:!1;useEffect14(()=>{if(!entity)return;let suppressedFields=animation&&animation.__getSuppressedFields?new Set(animation.__getSuppressedFields()??[]):new Set;suppressedFields.has("position")&&(last.current.position=void 0),suppressedFields.has("rotation")&&(last.current.rotation=void 0),suppressedFields.has("scale")&&(last.current.scale=void 0);let positionChanged=!suppressedFields.has("position")&&!shallowEqualVec3(last.current.position,position),rotationChanged=!suppressedFields.has("rotation")&&!shallowEqualRotation(last.current.rotation,rotation),scaleChanged=!suppressedFields.has("scale")&&!shallowEqualVec3(last.current.scale,scale);if(suppressedFields.has("position")||(last.current.position=position),suppressedFields.has("rotation")||(last.current.rotation=rotation),suppressedFields.has("scale")||(last.current.scale=scale),!(positionChanged||rotationChanged||scaleChanged))return;let update={};return positionChanged&&position&&(update.position=position),rotationChanged&&rotation&&(update.rotation=rotation),scaleChanged&&scale&&(update.scale=scale),Object.keys(update).length===0?void 0:((async()=>{try{await entity.updateTransform(update)}catch(err){console.error("[useEntityTransform] Failed to update transform:",err)}})(),()=>{})},[entity,position,rotation,scale,animation,isAnimating])}import{useEffect as useEffect15,useRef as useRef9}from"react";var eventMap={onSpatialTap:"spatialtap",onSpatialDragStart:"spatialdragstart",onSpatialDrag:"spatialdrag",onSpatialDragEnd:"spatialdragend",onSpatialRotate:"spatialrotate",onSpatialRotateEnd:"spatialrotateend",onSpatialMagnify:"spatialmagnify",onSpatialMagnifyEnd:"spatialmagnifyend"};import{useImperativeHandle}from"react";var useEntityRef=(ref,instance)=>{useImperativeHandle(ref,()=>instance)},EntityRef=class{_entity;_ctx;constructor(entity=null,ctx=null){this._entity=entity,this._ctx=ctx}updateEntity(entity){entity&&(this._entity=entity)}updateCtx(ctx){ctx&&(this._ctx=ctx)}destroy(){this._entity?.destroy()}get entity(){return this._entity}get id(){return this._entity?.userData?.id}get name(){return this._entity?.userData?.name}async convertFromEntityToEntity(fromEntityId,toEntityId,position){if(!this._entity)return position;try{let fromEnt=await this._ctx?.resourceRegistry.get(fromEntityId),toEnt=await this._ctx?.resourceRegistry.get(toEntityId);return!fromEnt||!toEnt?position:(await this._entity.convertFromEntityToEntity(fromEnt.id,toEnt.id,position))?.data??position}catch{return position}}async convertFromEntityToReality(entityId,position){if(!this._entity)return position;try{let ent=await this._ctx?.resourceRegistry.get(entityId);return ent?(await this._entity.convertFromEntityToScene(ent.id,position))?.data??position:position}catch{return position}}async convertFromRealityToEntity(entityId,position){if(!this._entity)return position;try{let ent=await this._ctx?.resourceRegistry.get(entityId);return ent?(await this._entity.convertFromSceneToEntity(ent.id,position))?.data??position:position}catch{return position}}};function createEventProxy2(ev,instance){return new Proxy(ev,{get(target,prop){if(prop==="currentTarget")return instance;if(prop==="target"){let origin=target.__origin;return origin?new EntityRef(origin,null):instance}if(prop==="bubbles")return!0;if(prop==="offsetX"){let type=target.type;return type==="spatialtap"?target.detail?.location3D?.x??0:type==="spatialdragstart"?target.detail?.startLocation3D?.x??0:void 0}if(prop==="offsetY"){let type=target.type;return type==="spatialtap"?target.detail?.location3D?.y??0:type==="spatialdragstart"?target.detail?.startLocation3D?.y??0:void 0}if(prop==="offsetZ"){let type=target.type;return type==="spatialtap"?target.detail?.location3D?.z??0:type==="spatialdragstart"?target.detail?.startLocation3D?.z??0:void 0}if(prop==="translationX")return target.type==="spatialdrag"?target.detail?.translation3D?.x??0:void 0;if(prop==="translationY")return target.type==="spatialdrag"?target.detail?.translation3D?.y??0:void 0;if(prop==="translationZ")return target.type==="spatialdrag"?target.detail?.translation3D?.z??0:void 0;if(prop==="quaternion")return target.type==="spatialrotate"?target.detail?.quaternion??{x:0,y:0,z:0,w:1}:void 0;if(prop==="magnification")return target.type==="spatialmagnify"?target.detail?.magnification??1:void 0;if(prop==="clientX"){let type=target.type;return type==="spatialtap"||type==="spatialdragstart"?target.detail?.globalLocation3D?.x??0:void 0}if(prop==="clientY"){let type=target.type;return type==="spatialtap"||type==="spatialdragstart"?target.detail?.globalLocation3D?.y??0:void 0}if(prop==="clientZ"){let type=target.type;return type==="spatialtap"||type==="spatialdragstart"?target.detail?.globalLocation3D?.z??0:void 0}let val=target[prop];return typeof val=="function"?val.bind(target):val}})}var useEntityEvent=({instance,...handlers})=>{let eventsSetRef=useRef9(new Set);return useEffect15(()=>{let entity=instance.entity;if(entity)return Object.entries(eventMap).forEach(([reactKey,spatialEvent])=>{let handlerFn=handlers[reactKey];if(!handlerFn)return;let wrapped=ev=>handlerFn(createEventProxy2(ev,instance));entity.addEvent(spatialEvent,wrapped),eventsSetRef.current.add(reactKey)}),()=>{}},[instance.entity,...Object.values(handlers)]),useEffect15(()=>{let entity=instance.entity;if(entity)return()=>{for(let x of eventsSetRef.current)entity.removeEvent(x);eventsSetRef.current.clear()}},[instance.entity]),null};import{useEffect as useEffect16,useRef as useRef10}from"react";function createEventProxy3(ev,instance){return new Proxy(ev,{get(target,prop){if(prop==="currentTarget")return instance;if(prop==="target"){let origin=target.__origin;return origin?new EntityRef(origin,null):instance}if(prop==="bubbles")return!0;if(prop==="offsetX"){let type=target.type;return type==="spatialtap"?target.detail?.location3D?.x??0:type==="spatialdragstart"?target.detail?.startLocation3D?.x??0:void 0}if(prop==="offsetY"){let type=target.type;return type==="spatialtap"?target.detail?.location3D?.y??0:type==="spatialdragstart"?target.detail?.startLocation3D?.y??0:void 0}if(prop==="offsetZ"){let type=target.type;return type==="spatialtap"?target.detail?.location3D?.z??0:type==="spatialdragstart"?target.detail?.startLocation3D?.z??0:void 0}if(prop==="translationX")return target.type==="spatialdrag"?target.detail?.translation3D?.x??0:void 0;if(prop==="translationY")return target.type==="spatialdrag"?target.detail?.translation3D?.y??0:void 0;if(prop==="translationZ")return target.type==="spatialdrag"?target.detail?.translation3D?.z??0:void 0;if(prop==="quaternion")return target.type==="spatialrotate"?target.detail?.quaternion??{x:0,y:0,z:0,w:1}:void 0;if(prop==="magnification")return target.type==="spatialmagnify"?target.detail?.magnification??1:void 0;if(prop==="clientX"){let type=target.type;return type==="spatialtap"||type==="spatialdragstart"?target.detail?.globalLocation3D?.x??0:void 0}if(prop==="clientY"){let type=target.type;return type==="spatialtap"||type==="spatialdragstart"?target.detail?.globalLocation3D?.y??0:void 0}if(prop==="clientZ"){let type=target.type;return type==="spatialtap"||type==="spatialdragstart"?target.detail?.globalLocation3D?.z??0:void 0}let val=target[prop];return typeof val=="function"?val.bind(target):val}})}var useRealityEvents=({instance,...handlers})=>{let eventsSetRef=useRef10(new Set);useEffect16(()=>{if(instance)return Object.entries(eventMap).forEach(([reactKey,spatialEvent])=>{let handlerFn=handlers[reactKey];if(!handlerFn)return;let wrapped=ev=>handlerFn(createEventProxy3(ev,instance));instance.addEvent(spatialEvent,wrapped),eventsSetRef.current.add(spatialEvent)}),()=>{if(instance){for(let x of eventsSetRef.current)instance.removeEvent(x);eventsSetRef.current.clear()}}},[instance,...Object.values(handlers)])};import{useEffect as useEffect17}from"react";var useEntityId=({id,entity})=>{let ctx=useRealityContext();return useEffect17(()=>{if(!(!id||!entity||!ctx))return ctx.resourceRegistry.add(id,Promise.resolve(entity)),()=>{ctx.resourceRegistry.remove(id)}},[id,entity,ctx]),null};import{useEffect as useEffect18,useRef as useRef11}from"react";var useEntity=({ref,id,position,rotation,scale,enableInput,animation,onSpatialTap,onSpatialDragStart,onSpatialDrag,onSpatialDragEnd,onSpatialRotate,onSpatialRotateEnd,onSpatialMagnify,onSpatialMagnifyEnd,createEntity,recreateKey})=>{let ctx=useRealityContext(),parent=useParentContext(),instanceRef=useRef11(new EntityRef(null,ctx)),forceUpdate=useForceUpdate2(),prevAnimationRef=useRef11(void 0);return useEffect18(()=>{if(!ctx)return;let controller=new AbortController;return(async()=>{try{let ent=await createEntity(controller.signal);if(!ent)return;if(controller.signal.aborted){ent.destroy();return}if(await ent.updateTransform({position,rotation,scale}),controller.signal.aborted){ent.destroy();return}if(parent){if(!(await parent.addEntity(ent)).success)throw new Error("parent.addEntity failed")}else if(!(await ctx.reality.addEntity(ent)).success)throw new Error("ctx.reality.addEntity failed");instanceRef.current?.updateEntity(ent),animation&&(animation.__bind?.(ent),prevAnimationRef.current=animation),forceUpdate()}catch(error){console.error("useEntity init ~ error:",error)}})(),()=>{controller.abort(),prevAnimationRef.current&&(prevAnimationRef.current.__unbind?.(),prevAnimationRef.current=void 0),instanceRef.current?.destroy()}},[ctx,parent,recreateKey]),useEffect18(()=>{let entity=instanceRef.current.entity;if(!entity)return;let prevAnimation=prevAnimationRef.current;prevAnimation!==animation&&(prevAnimation&&prevAnimation.__unbind?.(),animation&&animation.__bind?.(entity),prevAnimationRef.current=animation)},[animation,instanceRef.current.entity]),useEntityId({id,entity:instanceRef.current.entity}),useEntityTransform(instanceRef.current.entity,{position,rotation,scale,animation}),useEntityRef(ref,instanceRef.current),useEntityEvent({instance:instanceRef.current,onSpatialTap,onSpatialDragStart,onSpatialDrag,onSpatialDragEnd,onSpatialRotate,onSpatialRotateEnd,onSpatialMagnify,onSpatialMagnifyEnd}),useEffect18(()=>{let ent=instanceRef.current.entity;ent&&enableInput!==void 0&&(ent.enableInput=!!enableInput)},[instanceRef.current.entity,enableInput]),instanceRef.current.entity};import{useCallback as useCallback10,useState as useState6}from"react";var useForceUpdate2=()=>{let[,setTick]=useState6(0);return useCallback10(()=>setTick(tick=>tick+1),[])};import{useCallback as useCallback11,useEffect as useEffect19,useMemo as useMemo5,useRef as useRef12,useReducer as useReducer2}from"react";import{composeSRT}from"@webspatial/core-sdk";var VALID_TIMING_FUNCTIONS=["linear","easeIn","easeOut","easeInOut"];function validateAnimationConfig(config){if(!config.to)throw new Error("[useAnimation] config.to is required");if(!(config.to.position!==void 0||config.to.rotation!==void 0||config.to.scale!==void 0))throw new Error("[useAnimation] config.to must specify at least one of position, rotation, or scale");if(config.duration!==void 0&&(typeof config.duration!="number"||!isFinite(config.duration)||config.duration<=0))throw new Error("[useAnimation] config.duration must be a positive finite number");if(config.delay!==void 0&&(typeof config.delay!="number"||!isFinite(config.delay)||config.delay<0))throw new Error("[useAnimation] config.delay must be a non-negative finite number");if(config.timingFunction!==void 0&&!VALID_TIMING_FUNCTIONS.includes(config.timingFunction))throw new Error(`[useAnimation] config.timingFunction must be one of: ${VALID_TIMING_FUNCTIONS.join(", ")}`);if(config.loop!==void 0&&config.loop!==!1&&config.loop!==!0)if(typeof config.loop=="object"&&config.loop!==null){let keys=Object.keys(config.loop);for(let k of keys)if(k!=="reverse")throw new Error(`[useAnimation] config.loop object contains unknown key "${k}"`);if(config.loop.reverse!==void 0&&typeof config.loop.reverse!="boolean")throw new Error("[useAnimation] config.loop.reverse must be a boolean")}else throw new Error("[useAnimation] config.loop must be true, false, undefined, or { reverse?: boolean }");if(config.playbackRate!==void 0&&(typeof config.playbackRate!="number"||!isFinite(config.playbackRate)||config.playbackRate<=0))throw new Error("[useAnimation] config.playbackRate must be a positive finite number (> 0)");config.to.position&&validateVec3(config.to.position,"to.position"),config.to.rotation&&validateVec3(config.to.rotation,"to.rotation"),config.to.scale&&validateScaleVec3(config.to.scale,"to.scale"),config.from&&(config.from.position&&validateVec3(config.from.position,"from.position"),config.from.rotation&&validateVec3(config.from.rotation,"from.rotation"),config.from.scale&&validateScaleVec3(config.from.scale,"from.scale"))}function validateVec3(v,label){if(!isFinite(v.x)||!isFinite(v.y)||!isFinite(v.z))throw new Error(`[useAnimation] config.${label} components must be finite numbers`)}function validateScaleVec3(v,label){if(validateVec3(v,label),v.x<0||v.y<0||v.z<0)throw new Error(`[useAnimation] config.${label} components must be non-negative`)}function getAnimatedFields(config){let fields=[];return config.to.position!==void 0&&fields.push("position"),config.to.rotation!==void 0&&fields.push("rotation"),config.to.scale!==void 0&&fields.push("scale"),fields}var _animObjectCounter=0;function nextAnimObjectId(){return`__anim_${++_animObjectCounter}_${Date.now()}`}var _sessionCounter=0;function nextAnimationId(){return`anim_${++_sessionCounter}_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}var _boundAnimations=new WeakMap;function useEntityAnimation(config,active=!0){active&&validateAnimationConfig(config);let animatedFields=useMemo5(()=>getAnimatedFields(config),[config.to.position!==void 0,config.to.rotation!==void 0,config.to.scale!==void 0]),animObjectId=useRef12(nextAnimObjectId()).current,configRef=useRef12(config);configRef.current=config;let sessionRef=useRef12(null),entityRef=useRef12(null),unmountedRef=useRef12(!1),finishedRef=useRef12(!1),[,bumpSyncVersion]=useReducer2(x=>x+1,0),commandQueueRef=useRef12(Promise.resolve()),enqueueCommand=useCallback11(fn=>{commandQueueRef.current=commandQueueRef.current.then(fn,fn)},[]),reportError=useCallback11(error=>{if(unmountedRef.current)return;let cfg=configRef.current;cfg.onError?cfg.onError(error):console.error("[useEntityAnimation] Animation error:",error)},[]),toMatrix=useCallback11((values,entity)=>{let pos=values.position??entity.position,rot=values.rotation??entity.rotation,scl=values.scale??entity.scale;return composeSRT(pos,rot,scl).toFloat64Array()},[]),doPlay=useCallback11(async(session,entity)=>{let cfg=session.config,cmd={animationId:session.animationId,type:"play",entityId:entity.id,duration:cfg.duration??.3,timingFunction:cfg.timingFunction??"easeInOut",delay:cfg.delay??0,loop:cfg.loop,playbackRate:cfg.playbackRate},toValues={};if(cfg.to.position&&(toValues.position=cfg.to.position),cfg.to.rotation&&(toValues.rotation=cfg.to.rotation),cfg.to.scale&&(toValues.scale=cfg.to.scale),cmd.toTransform=toMatrix(toValues,entity),cfg.from){let fromValues={};cfg.from.position&&(fromValues.position=cfg.from.position),cfg.from.rotation&&(fromValues.rotation=cfg.from.rotation),cfg.from.scale&&(fromValues.scale=cfg.from.scale),cmd.fromTransform=toMatrix(fromValues,entity)}try{let result=await entity.animateTransform(cmd);if(session.result=result,sessionRef.current!==session||session.unmounted)return;session.queuedPause?session.state="paused":(cfg.delay??0)>0?session.state="delaying":session.state="running",!session.unmounted&&cfg.onStart&&cfg.onStart(),result.finished.then(values=>{sessionRef.current!==session||session.unmounted||(session.state="finished",finishedRef.current=!0,sessionRef.current=null,!session.unmounted&&cfg.onComplete&&cfg.onComplete(values),bumpSyncVersion())}),result.canceled.then(values=>{session.unmounted||(sessionRef.current===session&&(session.state="idle",sessionRef.current=null),finishedRef.current=!1,cfg.onCancel&&cfg.onCancel(values),bumpSyncVersion())}),result.failed&&result.failed.then(error=>{sessionRef.current!==session||session.unmounted||(session.state="idle",sessionRef.current=null,reportError(error))})}catch(err){if(sessionRef.current!==session||session.unmounted)return;session.state="idle",sessionRef.current=null,reportError({animationId:session.animationId,command:"play",reason:err?.message??String(err)})}},[toMatrix,reportError]),doCancel=useCallback11(async(session,entity)=>{if(session.state==="queued"){session.state="idle";return}try{await entity.animateTransform({animationId:session.animationId,type:"cancel"})}catch(err){throw reportError({animationId:session.animationId,command:"cancel",reason:err?.message??String(err)}),err}},[reportError]),play=useCallback11(()=>{let currentSession=sessionRef.current,entity=entityRef.current;if(currentSession&&(currentSession.state==="running"||currentSession.state==="delaying"||currentSession.state==="queued"))return;if(currentSession&¤tSession.state==="paused"){if(currentSession.queuedPause){currentSession.queuedPause=!1,currentSession.state="queued";return}enqueueCommand(async()=>{if(!(!entity||currentSession!==sessionRef.current||currentSession.unmounted)&¤tSession.state==="paused")try{await entity.animateTransform({animationId:currentSession.animationId,type:"resume"}),currentSession.state="running",bumpSyncVersion()}catch(err){reportError({animationId:currentSession.animationId,command:"resume",reason:err?.message??String(err)})}});return}let cfg=configRef.current,prevSession=currentSession,newSession={animationId:nextAnimationId(),state:entity?"running":"queued",fields:getAnimatedFields(cfg),config:{...cfg}};finishedRef.current=!1,enqueueCommand(async()=>{if(!unmountedRef.current){if(prevSession&&prevSession.state!=="idle"&&prevSession.state!=="finished")try{entity&&await doCancel(prevSession,entity),prevSession.state="idle",!prevSession.unmounted&&prevSession.config.onCancel&&prevSession.config.onCancel({position:entity?.position,rotation:entity?.rotation,scale:entity?.scale})}catch{return}sessionRef.current=newSession,bumpSyncVersion(),entity&&await doPlay(newSession,entity)}})},[enqueueCommand,doCancel,doPlay,reportError]),pause=useCallback11(()=>{let session=sessionRef.current;if(!session||session.state==="idle")return;let entity=entityRef.current;if(session.state==="queued"){session.queuedPause=!0,session.state="paused",bumpSyncVersion();return}enqueueCommand(async()=>{if(!(!entity||session!==sessionRef.current||session.unmounted)&&!(session.state!=="delaying"&&session.state!=="running"))try{await entity.animateTransform({animationId:session.animationId,type:"pause"}),session.state="paused",bumpSyncVersion()}catch(err){reportError({animationId:session.animationId,command:"pause",reason:err?.message??String(err)})}})},[enqueueCommand,reportError]),cancel=useCallback11(()=>{let session=sessionRef.current;if(!session||session.state==="idle"||session.state==="finished")return;let entity=entityRef.current;if(session.state==="queued"){session.state="idle",sessionRef.current=null,session.config.onCancel&&session.config.onCancel({position:entity?.position,rotation:entity?.rotation,scale:entity?.scale}),bumpSyncVersion();return}enqueueCommand(async()=>{if(!(!entity||session!==sessionRef.current||session.unmounted)&&!(session.state==="idle"||session.state==="finished"))try{await doCancel(session,entity),session.state="idle",sessionRef.current=null;let cfg=session.config,restoreValues={};cfg.from&&(cfg.from.position&&(restoreValues.position=cfg.from.position),cfg.from.rotation&&(restoreValues.rotation=cfg.from.rotation),cfg.from.scale&&(restoreValues.scale=cfg.from.scale)),Object.keys(restoreValues).length>0&&await entity.updateTransform(restoreValues)}catch{}})},[enqueueCommand,doCancel]),api=useMemo5(()=>({play,pause,cancel,get isAnimating(){let s=sessionRef.current;return s?s.state==="queued"||s.state==="delaying"||s.state==="running":!1},get isPaused(){let s=sessionRef.current;return s?s.state==="paused":!1},get playState(){let s=sessionRef.current;if(!s)return finishedRef.current?"finished":"idle";switch(s.state){case"queued":return"queued";case"delaying":case"running":return"running";case"paused":return"paused";case"finished":return"finished";case"idle":default:return"idle"}},get finished(){return finishedRef.current}}),[play,pause,cancel]),animatedProps=useMemo5(()=>({__animationObjectId:animObjectId,__animatedFields:animatedFields,get __animating(){let s=sessionRef.current;return s!==null&&s.state!=="idle"}}),[animObjectId,animatedFields]);return animatedProps.__bind=entity=>{entityRef.current=entity;let existingId=_boundAnimations.get(animatedProps);if(existingId&&existingId!==entity.id)throw new Error("[useEntityAnimation] The same animation object must not be bound to multiple entities.");_boundAnimations.set(animatedProps,entity.id);let session=sessionRef.current;session&&session.state==="queued"&&enqueueCommand(async()=>{session!==sessionRef.current||session.unmounted||await doPlay(session,entity)})},animatedProps.__unbind=()=>{let entity=entityRef.current,session=sessionRef.current;session&&entity&&(session.unmounted=!0,session.state!=="idle"&&session.state!=="queued"&&(entity.animateTransform({animationId:session.animationId,type:"cancel"}).catch(()=>{}),entity.cleanupAnimationListeners(session.animationId)),sessionRef.current=null),_boundAnimations.delete(animatedProps),entityRef.current=null},animatedProps.__getSuppressedFields=()=>{let session=sessionRef.current;return!session||session.state==="idle"?null:session.fields},useEffect19(()=>{if(active)return unmountedRef.current=!1,()=>{unmountedRef.current=!0;let session=sessionRef.current;session&&(session.unmounted=!0)}},[active]),useEffect19(()=>{if(!active)return;config.autoStart!==!1&&!sessionRef.current&&play()},[active]),[animatedProps,api]}import{jsx as jsx8}from"react/jsx-runtime";var BaseEntity=forwardRef8(({children,createEntity,recreateKey,...rest},ref)=>{let ctx=useRealityContext(),entity=useEntity({...rest,ref,recreateKey,createEntity:signal=>createEntity(ctx,signal)});return entity?jsx8(ParentContext.Provider,{value:entity,children}):null});import{jsx as jsx9}from"react/jsx-runtime";var Entity=forwardRef9((props,ref)=>{let{id,name,children,...rest}=props;return jsx9(BaseEntity,{...rest,id,ref,createEntity:async ctxVal=>ctxVal.session.createEntity({id,name}),children})});import{forwardRef as forwardRef11}from"react";import{forwardRef as forwardRef10,useEffect as useEffect20,useRef as useRef13}from"react";import{jsx as jsx10}from"react/jsx-runtime";var GeometryEntity=forwardRef10(({id,children,name,materials,geometryOptions,createGeometry,...rest},ref)=>{let ctx=useRealityContext(),entityRef=useRef13(null),componentRef=useRef13(null),mutableRef=useRef13({lastSnapshot:null,rebuildGen:0});return useEffect20(()=>{let{lastSnapshot}=mutableRef.current;if(!ctx||!entityRef.current||lastSnapshot===null)return;let geometryChanged=!shallowEqualObject(lastSnapshot.geometryOptions,geometryOptions),materialsChanged=!shallowEqualArray(lastSnapshot.materials,materials);if(!geometryChanged&&!materialsChanged)return;mutableRef.current.lastSnapshot={geometryOptions,materials},mutableRef.current.rebuildGen+=1;let gen=mutableRef.current.rebuildGen;(async()=>{let entity=entityRef.current;if(entity)try{let oldComponent=componentRef.current;if(oldComponent&&(await entity.removeComponent(oldComponent),await oldComponent.destroy(),componentRef.current=null,gen!==mutableRef.current.rebuildGen))return;let geometry=await createGeometry(geometryOptions);if(gen!==mutableRef.current.rebuildGen){await geometry.destroy();return}let materialList=await Promise.all(materials?.map(mid=>ctx.resourceRegistry.get(mid)).filter(Boolean)??[]);if(gen!==mutableRef.current.rebuildGen){await geometry.destroy();return}let modelComponent=await ctx.session.createModelComponent({mesh:geometry,materials:materialList});if(gen!==mutableRef.current.rebuildGen){await modelComponent.destroy(),await geometry.destroy();return}await entity.addComponent(modelComponent),componentRef.current=modelComponent}catch(error){gen===mutableRef.current.rebuildGen&&console.error("GeometryEntity: rebuild failed",error)}})()},[ctx,geometryOptions,materials,createGeometry]),jsx10(BaseEntity,{...rest,id,ref,createEntity:async(ctx2,signal)=>{let manager=new AbortResourceManager(signal);try{let ent=await manager.addResource(()=>ctx2.session.createEntity({id,name})),geometry=await manager.addResource(()=>createGeometry(geometryOptions)),materialList=await Promise.all(materials?.map(id2=>ctx2.resourceRegistry.get(id2)).filter(Boolean)??[]),modelComponent=await manager.addResource(()=>ctx2.session.createModelComponent({mesh:geometry,materials:materialList}));return await ent.addComponent(modelComponent),entityRef.current=ent,componentRef.current=modelComponent,mutableRef.current.lastSnapshot={geometryOptions,materials},ent}catch{return await manager.dispose(),null}},children})});import{jsx as jsx11}from"react/jsx-runtime";var BoxEntity=forwardRef11(({children,...props},ref)=>{let ctx=useRealityContext();return jsx11(GeometryEntity,{...props,ref,createGeometry:options=>ctx.session.createBoxGeometry(options),geometryOptions:{width:props.width,height:props.height,depth:props.depth,cornerRadius:props.cornerRadius,splitFaces:props.splitFaces},children})});import{useEffect as useEffect21,useRef as useRef14,useState as useState7}from"react";var UnlitMaterial=({children,...options})=>{let ctx=useRealityContext(),materialRef=useRef14(void 0),[isInitialized,setIsInitialized]=useState7(!1),[textureRevision,setTextureRevision]=useState7(0);return useEffect21(()=>{if(!(!ctx||!options.textureId))return ctx.resourceRegistry.subscribe(options.textureId,()=>{setTextureRevision(v=>v+1)})},[ctx,options.textureId]),useEffect21(()=>{if(!ctx)return;let cancelled=!1,materialId=options.id,{session,resourceRegistry}=ctx;return(async()=>{try{let textureIdForNative=options.textureId;if(options.textureId&&resourceRegistry.has(options.textureId))try{let textureResource=await resourceRegistry.get(options.textureId);if(cancelled)return;textureIdForNative=textureResource.id}catch{textureIdForNative=""}else options.textureId&&(textureIdForNative="");if(cancelled)return;let commandOptions={color:options.color,textureId:textureIdForNative,transparent:options.transparent,opacity:options.opacity},materialPromise=session.createUnlitMaterial(commandOptions);resourceRegistry.add(materialId,materialPromise);let mat=await materialPromise;if(cancelled)return;materialRef.current=mat,setIsInitialized(!0)}catch(error){console.error(" ~ UnlitMaterial ~ error:",error)}})(),()=>{cancelled=!0,resourceRegistry.removeAndDestroy(materialId),materialRef.current=void 0,setIsInitialized(!1)}},[ctx,options.id]),useEffect21(()=>{if(!ctx||!isInitialized||!materialRef.current)return;let cancelled=!1;return(async()=>{let updates={};if(options.color!==void 0&&(updates.color=options.color),options.transparent!==void 0&&(updates.transparent=options.transparent),options.opacity!==void 0&&(updates.opacity=options.opacity),options.textureId!==void 0)if(options.textureId==="")updates.textureId="";else if(!ctx.resourceRegistry.has(options.textureId))updates.textureId="";else{let texturePromise=ctx.resourceRegistry.get(options.textureId);try{let textureResource=await texturePromise;if(cancelled)return;updates.textureId=textureResource.id}catch{updates.textureId=""}}if(cancelled||Object.keys(updates).length===0)return;let mat=materialRef.current;mat&&mat.updateProperties(updates).catch(()=>{})})(),()=>{cancelled=!0}},[ctx,isInitialized,options.color,options.textureId,options.transparent,options.opacity,textureRevision]),null};import{useEffect as useEffect22,useRef as useRef15}from"react";function getAbsoluteUrl(url){if(typeof window>"u"||!window.location?.href)return url;try{return new URL(url,window.location.href).href}catch{return url}}var Texture=({children,id,url,onLoad,onError})=>{let ctx=useRealityContext(),textureRef=useRef15(null),urlRevisionRef=useRef15(0);return useEffect22(()=>{if(!ctx)return;let{resourceRegistry}=ctx,capturedId=id;return()=>{textureRef.current=null,resourceRegistry.removeAndDestroy(capturedId)}},[ctx,id]),useEffect22(()=>{if(!ctx)return;let{session,resourceRegistry}=ctx,revision=++urlRevisionRef.current,cancelled=!1;return(async()=>{let resolvedUrl=getAbsoluteUrl(url);try{if(textureRef.current){if(await textureRef.current.updateProperties({url:resolvedUrl}),cancelled||revision!==urlRevisionRef.current)return;resourceRegistry.notify(id),onLoad?.();return}let texturePromise=session.createTexture({url:resolvedUrl});resourceRegistry.add(id,texturePromise);let tex=await texturePromise;if(cancelled||revision!==urlRevisionRef.current){tex.destroy();return}textureRef.current=tex,onLoad?.()}catch(error){if(cancelled||revision!==urlRevisionRef.current)return;onError?.(error)}})(),()=>{cancelled=!0}},[ctx,id,url]),null};import{forwardRef as forwardRef12}from"react";import{jsx as jsx12}from"react/jsx-runtime";var SphereEntity=forwardRef12(({children,...props},ref)=>{let ctx=useRealityContext();return jsx12(GeometryEntity,{...props,ref,createGeometry:options=>ctx.session.createSphereGeometry(options),geometryOptions:{radius:props.radius},children})});import{forwardRef as forwardRef13}from"react";import{jsx as jsx13}from"react/jsx-runtime";var ConeEntity=forwardRef13(({children,...props},ref)=>{let ctx=useRealityContext();return jsx13(GeometryEntity,{...props,ref,createGeometry:options=>ctx.session.createConeGeometry(options),geometryOptions:{radius:props.radius,height:props.height},children})});import{forwardRef as forwardRef14}from"react";import{jsx as jsx14}from"react/jsx-runtime";var CylinderEntity=forwardRef14(({children,...props},ref)=>{let ctx=useRealityContext();return jsx14(GeometryEntity,{...props,ref,createGeometry:options=>ctx.session.createCylinderGeometry(options),geometryOptions:{radius:props.radius,height:props.height},children})});import{forwardRef as forwardRef15}from"react";import{jsx as jsx15}from"react/jsx-runtime";var PlaneEntity=forwardRef15(({children,...props},ref)=>{let ctx=useRealityContext();return jsx15(GeometryEntity,{...props,ref,createGeometry:options=>ctx.session.createPlaneGeometry(options),geometryOptions:{width:props.width,height:props.height,cornerRadius:props.cornerRadius},children})});import{jsx as jsx16}from"react/jsx-runtime";var SceneGraph=({children})=>jsx16(ParentContext.Provider,{value:null,children});import{useEffect as useEffect23,useRef as useRef16}from"react";var ModelAsset=({children,...options})=>{let ctx=useRealityContext(),materialRef=useRef16(void 0);return useEffect23(()=>{let controller=new AbortController;if(!ctx)return;let{session,resourceRegistry}=ctx;return(async()=>{try{let resolvedUrl=getAbsoluteUrl(options.src),modelAssetPromise=session.createModelAsset({url:resolvedUrl});resourceRegistry.add(options.id,modelAssetPromise);let mat=await modelAssetPromise;if(controller.signal.aborted){mat.destroy();return}materialRef.current=mat,options.onLoad?.()}catch(error){options.onError?.(error)}})(),()=>{controller.abort(),materialRef.current?.destroy()}},[ctx]),null};import{forwardRef as forwardRef16,useEffect as useEffect24,useRef as useRef17}from"react";import{jsx as jsx17}from"react/jsx-runtime";var ModelEntity=forwardRef16(({id,model,children,name,materials,...rest},ref)=>{let ctx=useRealityContext(),entityRef=useRef17(null),lastMaterialsRef=useRef17(void 0);return useEffect24(()=>{if(!ctx||!entityRef.current)return;let next=materials??[],prev=lastMaterialsRef.current??[];if(shallowEqualArray(prev,next))return;lastMaterialsRef.current=next,(async()=>{try{let materialList=(await Promise.all(next.map(mid=>ctx.resourceRegistry.get(mid)))).filter(Boolean);entityRef.current&&await entityRef.current.setMaterials(materialList)}catch(error){console.error("ModelEntity: failed to set materials",error)}})()},[ctx,materials]),jsx17(BaseEntity,{...rest,id,ref,recreateKey:model,createEntity:async(ctx2,signal)=>{try{let modelAsset=await ctx2.resourceRegistry.get(model);if(!modelAsset)throw new Error(`ModelEntity: model not found ${model}`);if(signal.aborted)return null;let ent=await ctx2.session.createSpatialModelEntity({modelAssetId:modelAsset.id,name},{id,name});if(entityRef.current=ent,materials&&materials.length>0){let materialList=(await Promise.all(materials.map(mid=>ctx2.resourceRegistry.get(mid)))).filter(Boolean);materialList.length>0&&!signal.aborted&&await ent.setMaterials(materialList)}return lastMaterialsRef.current=materials??[],ent}catch{return null}},children})});import{forwardRef as forwardRef17,useCallback as useCallback12,useEffect as useEffect25,useRef as useRef18,useState as useState8}from"react";import{Fragment as Fragment3,jsx as jsx18,jsxs as jsxs3}from"react/jsx-runtime";var Reality=forwardRef17(function({children,...inProps},ref){if(useInsideAttachment())return console.warn("[WebSpatial] Reality cannot be used inside AttachmentAsset."),null;let{onSpatialTap,onSpatialDragStart,onSpatialDrag,onSpatialDragEnd,onSpatialRotate,onSpatialRotateEnd,onSpatialMagnify,onSpatialMagnifyEnd,"xr-animation":xrAnimation,...props}=inProps,ctxRef=useRef18(null),creationId=useRef18(0),[isReady,setIsReady]=useState8(!1),cleanupReality=useCallback12(()=>{ctxRef.current?.attachmentRegistry.destroy(),ctxRef.current?.resourceRegistry.destroy(),ctxRef.current?.reality.destroy(),ctxRef.current=null,setIsReady(!1)},[]);useEffect25(()=>()=>{creationId.current++,cleanupReality()},[cleanupReality]);let createReality=useCallback12(async()=>{let id=++creationId.current,resourceRegistry=new ResourceRegistry,attachmentRegistry=new AttachmentRegistry,session=getSession();if(!session)return resourceRegistry.destroy(),attachmentRegistry.destroy(),null;let reality=await session.createSpatializedDynamic3DElement(),isCancelled=()=>id!==creationId.current;if(isCancelled())return resourceRegistry.destroy(),attachmentRegistry.destroy(),reality.destroy(),null;try{return!(await session.getSpatialScene().addSpatializedElement(reality)).success||isCancelled()?(resourceRegistry.destroy(),attachmentRegistry.destroy(),reality.destroy(),null):(cleanupReality(),ctxRef.current={session,reality,resourceRegistry,attachmentRegistry},setIsReady(!0),reality)}catch(err){return console.error("[createReality] failed",err),resourceRegistry.destroy(),attachmentRegistry.destroy(),reality.destroy(),null}},[cleanupReality]),content=useCallback12(()=>jsx18(Fragment3,{}),[]);return useRealityEvents({instance:ctxRef.current?.reality??null,onSpatialTap,onSpatialDragStart,onSpatialDrag,onSpatialDragEnd,onSpatialRotate,onSpatialRotateEnd,onSpatialMagnify,onSpatialMagnifyEnd}),jsxs3(RealityContext.Provider,{value:ctxRef.current,children:[jsx18(SpatializedContainer,{component:"div",ref,"xr-animation":xrAnimation,createSpatializedElement:createReality,spatializedContent:content,...props}),isReady&&children]})});markWebSpatialPrimitive(Reality,"Reality");import{useEffect as useEffect26,useState as useState9}from"react";import{createPortal as createPortal3}from"react-dom";import{jsx as jsx19}from"react/jsx-runtime";var AttachmentAsset=({name,children})=>{let ctx=useRealityContext(),[containers,setContainers]=useState9([]);return useEffect26(()=>{if(ctx)return ctx.attachmentRegistry.onContainersChange(name,setContainers)},[ctx,name]),containers.length?jsx19(InsideAttachmentContext.Provider,{value:!0,children:containers.map(({instanceId,container})=>createPortal3(children,container,instanceId))}):null};import{useEffect as useEffect27,useRef as useRef19,useState as useState10}from"react";var instanceCounter=0,AttachmentEntity=({attachment:attachmentName,position,size})=>{let ctx=useRealityContext(),parent=useParentContext(),attachmentRef=useRef19(null),parentIdRef=useRef19(null),instanceIdRef=useRef19(`att_${++instanceCounter}`),attachmentNameRef=useRef19(attachmentName),[childWindow,setChildWindow]=useState10(null);return useEffect27(()=>{if(!ctx||!parent||attachmentRef.current)return;let parentId=parent.id;parentIdRef.current=parentId;let cancelled=!1;return(async()=>{try{let att=await ctx.session.createAttachmentEntity({parentEntityId:parentId,position:position??[0,0,0],size,ownerViewId:ctx.reality.id});if(cancelled){att.destroy();return}let windowProxy=att.getWindowProxy();if(setOpenWindowStyle(windowProxy),windowProxy.document.body.style.display="block",windowProxy.document.body.style.minWidth="100%",windowProxy.document.body.style.maxWidth="100%",windowProxy.document.body.style.minHeight="100%",!windowProxy.document.querySelector('meta[name="viewport"]')){let meta=windowProxy.document.createElement("meta");meta.name="viewport",meta.content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no",windowProxy.document.head.appendChild(meta)}let base=windowProxy.document.createElement("base");base.href=document.baseURI,windowProxy.document.head.appendChild(base),attachmentRef.current=att,setChildWindow(windowProxy),ctx.attachmentRegistry.addContainer(attachmentNameRef.current,instanceIdRef.current,att.getContainer())}catch(error){console.error("[AttachmentEntity] init error:",error)}})(),()=>{cancelled=!0;let att=attachmentRef.current;att&&(ctx.attachmentRegistry.removeContainer(attachmentNameRef.current,instanceIdRef.current),att.destroy(),attachmentRef.current=null,setChildWindow(null))}},[ctx,parent]),useEffect27(()=>{if(!ctx)return;let att=attachmentRef.current,prevName=attachmentNameRef.current;att&&prevName!==attachmentName&&(ctx.attachmentRegistry.removeContainer(prevName,instanceIdRef.current),ctx.attachmentRegistry.addContainer(attachmentName,instanceIdRef.current,att.getContainer())),attachmentNameRef.current=attachmentName},[ctx,attachmentName]),useSyncHeadStyles(childWindow),useEffect27(()=>{attachmentRef.current&&attachmentRef.current.update({position,size})},[position?.[0],position?.[1],position?.[2],size?.width,size?.height]),null};import{jsx as jsx20}from"react/jsx-runtime";var Material=props=>{if(props.type==="unlit"){let{type,...rest}=props;return jsx20(UnlitMaterial,{...rest})}return null};import{useSyncExternalStore}from"react";import{PhysicalMetrics}from"@webspatial/core-sdk";function useMetrics(){useSyncExternalStore(PhysicalMetrics.subscribe,PhysicalMetrics.getValue);let{pointToPhysical,physicalToPoint}=PhysicalMetrics;return{pointToPhysical,physicalToPoint}}import{forwardRef as forwardRef19}from"react";import{useRef as useRef20,useEffect as useEffect28,useMemo as useMemo6}from"react";function useMonitorDomChange(inRef){let ref=useRef20(null);return useEffect28(()=>{let observer=new MutationObserver(mutationsList=>{notifyDOMUpdate(mutationsList)}),config={childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class"]};return ref.current&&observer.observe(ref.current,config),()=>{observer.disconnect()}},[]),useMemo6(()=>new Proxy(ref,{set:function(target,key,value){return key==="current"&&inRef&&(typeof inRef=="function"?inRef(value):inRef&&(inRef.current=value)),Reflect.set(target,key,value)}}),[])}import{useEffect as useEffect29}from"react";function useMonitorDocumentHeaderChange(){useEffect29(()=>{let observer=new MutationObserver(mutationsList=>{notifyUpdateStandInstanceLayout()}),config={childList:!0,subtree:!0,attributes:!0};return observer.observe(document.head,config),()=>{observer.disconnect()}},[])}import{forwardRef as forwardRef18}from"react";import{jsx as jsx21}from"react/jsx-runtime";function SpatialMonitorBase(inProps,inRef){let{El="div",...props}=inProps,ref=useMonitorDomChange(inRef);return useMonitorDocumentHeaderChange(),jsx21(El,{...props,ref})}var SpatialMonitor=forwardRef18(SpatialMonitorBase);import{jsx as jsx22}from"react/jsx-runtime";var cachedWithSpatialMonitorType=new Map;function withSpatialMonitor(El){if(cachedWithSpatialMonitorType.has(El))return cachedWithSpatialMonitorType.get(El);{let WithSpatialMonitorComponent=forwardRef19((givenProps,givenRef)=>{let{El:_,...props}=givenProps;return jsx22(SpatialMonitor,{El,...props,ref:givenRef})});return WithSpatialMonitorComponent.displayName=`WithSpatialMonitor(${typeof El=="string"?El:El.displayName||El.name})`,cachedWithSpatialMonitorType.set(El,WithSpatialMonitorComponent),cachedWithSpatialMonitorType.set(cachedWithSpatialMonitorType,cachedWithSpatialMonitorType),WithSpatialMonitorComponent}}typeof window<"u"&&initPolyfill();export{getSession,withSpatialized2DElementContainer,useAnimation,Model,eventMap,useEntityAnimation,Entity,BoxEntity,UnlitMaterial,Texture,SphereEntity,ConeEntity,CylinderEntity,PlaneEntity,SceneGraph,ModelAsset,ModelEntity,Reality,AttachmentAsset,AttachmentEntity,Material,useMetrics,withSpatialMonitor,spatial_exports};
|
|
19
|
+
//# sourceMappingURL=chunk-WDOPCAA3.js.map
|