@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.
Files changed (66) hide show
  1. package/README.md +265 -4
  2. package/dist/Model-DO5ps8NA.d.ts +35 -0
  3. package/dist/Reality-BDyKL6th.d.ts +256 -0
  4. package/dist/Reality-DO-itiWW.d.ts +33 -0
  5. package/dist/SceneGraph-DxH74y6-.d.ts +214 -0
  6. package/dist/chunk-6JSRUX7P.js +2 -0
  7. package/dist/chunk-6JSRUX7P.js.map +1 -0
  8. package/dist/chunk-BTLTBCA7.js +2 -0
  9. package/dist/chunk-BTLTBCA7.js.map +1 -0
  10. package/dist/chunk-GG2QK5MA.js +2 -0
  11. package/dist/chunk-GG2QK5MA.js.map +1 -0
  12. package/dist/chunk-IOLNY4GP.js +2 -0
  13. package/dist/chunk-IOLNY4GP.js.map +1 -0
  14. package/dist/chunk-NWVQY6CN.js +2 -0
  15. package/dist/chunk-NWVQY6CN.js.map +1 -0
  16. package/dist/chunk-NXEOIP4Z.js +2 -0
  17. package/dist/chunk-NXEOIP4Z.js.map +1 -0
  18. package/dist/chunk-PDUEHFTO.js +2 -0
  19. package/dist/chunk-PDUEHFTO.js.map +1 -0
  20. package/dist/chunk-QHUROD77.js +2 -0
  21. package/dist/chunk-QHUROD77.js.map +1 -0
  22. package/dist/chunk-UHEO47WY.js +2 -0
  23. package/dist/chunk-UHEO47WY.js.map +1 -0
  24. package/dist/chunk-WDOPCAA3.js +19 -0
  25. package/dist/chunk-WDOPCAA3.js.map +1 -0
  26. package/dist/eager.d.ts +46 -0
  27. package/dist/eager.js +8 -0
  28. package/dist/eager.js.map +1 -0
  29. package/dist/experimental.d.ts +24 -0
  30. package/dist/experimental.js +8 -0
  31. package/dist/experimental.js.map +1 -0
  32. package/dist/index.d.ts +70 -0
  33. package/dist/index.js +8 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/internal/facades-client.d.ts +50 -0
  36. package/dist/internal/facades-client.js +3 -0
  37. package/dist/internal/facades-client.js.map +1 -0
  38. package/dist/jsx/jsx-dev-runtime.d.ts +7 -83
  39. package/dist/jsx/jsx-dev-runtime.js +1 -67
  40. package/dist/jsx/jsx-dev-runtime.js.map +1 -1
  41. package/dist/jsx/jsx-runtime.d.ts +81 -2
  42. package/dist/jsx/jsx-runtime.js +1 -67
  43. package/dist/jsx/jsx-runtime.js.map +1 -1
  44. package/dist/jsx-shared-CFDVUVpc.d.ts +16 -0
  45. package/dist/motionBindingTypes-CjxIC5bP.d.ts +25 -0
  46. package/dist/runtime/registerEagerEntry.d.ts +8 -0
  47. package/dist/runtime/registerEagerEntry.js +2 -0
  48. package/dist/runtime/registerEagerEntry.js.map +1 -0
  49. package/dist/spatial.d.ts +25 -0
  50. package/dist/spatial.js +7 -0
  51. package/dist/spatial.js.map +1 -0
  52. package/dist/useAnimation-C1LXt-xO.d.ts +28 -0
  53. package/dist/useMetrics-Bm_Urbtp.d.ts +96 -0
  54. package/package.json +51 -31
  55. package/dist/default/index.d.ts +0 -475
  56. package/dist/default/index.js +0 -4269
  57. package/dist/default/index.js.map +0 -1
  58. package/dist/jsx/jsx-dev-runtime.web.d.ts +0 -2
  59. package/dist/jsx/jsx-dev-runtime.web.js +0 -18
  60. package/dist/jsx/jsx-dev-runtime.web.js.map +0 -1
  61. package/dist/jsx/jsx-runtime.web.d.ts +0 -1
  62. package/dist/jsx/jsx-runtime.web.js +0 -18
  63. package/dist/jsx/jsx-runtime.web.js.map +0 -1
  64. package/dist/web/index.d.ts +0 -475
  65. package/dist/web/index.js +0 -4333
  66. package/dist/web/index.js.map +0 -1
package/dist/web/index.js DELETED
@@ -1,4333 +0,0 @@
1
-
2
- (function(){
3
- if(typeof window === 'undefined') return;
4
- if(!window.__webspatialsdk__) window.__webspatialsdk__ = {}
5
- window.__webspatialsdk__['react-sdk-version'] = "1.7.0"
6
- window.__webspatialsdk__['XR_ENV'] = "web"
7
- })()
8
-
9
-
10
- // src/spatialized-container/hooks/use2DFrameDetector.ts
11
- import {
12
- useContext,
13
- useLayoutEffect,
14
- useEffect,
15
- useCallback
16
- } from "react";
17
-
18
- // src/spatialized-container/context/SpatializedContainerContext.ts
19
- import { createContext } from "react";
20
-
21
- // src/spatialized-container/SpatialID.ts
22
- var SpatialID = "data-spatial-id";
23
-
24
- // src/spatialized-container/context/SpatializedContainerContext.ts
25
- var SpatializedContainerObject = class {
26
- dom = null;
27
- domSpatialId = null;
28
- fns = {};
29
- // cache dom for each spatialId
30
- spatialId2dom = {};
31
- spatialId2parentSpatialDom = {};
32
- // layer : [standardInstance sequence, portalInstance sequence]
33
- layerSequences = {};
34
- notify2DFramePlaceHolderChange(dom) {
35
- this.dom = dom;
36
- this.domSpatialId = dom.getAttribute(SpatialID);
37
- Object.values(this.fns).forEach((fn) => fn());
38
- }
39
- spatialId2transformVisibility = {};
40
- updateSpatialTransformVisibility(spatialId, spatialTransformVisibility) {
41
- this.spatialId2transformVisibility[spatialId] = spatialTransformVisibility;
42
- this.fnsForSpatialTransformVisibility[spatialId]?.forEach(
43
- (fn) => fn(spatialTransformVisibility)
44
- );
45
- }
46
- // this is used by onSpatialEvent.currentTarget property
47
- spatialId2ContainerRefProxy = {};
48
- // this is called in sub standardInstance env
49
- updateSpatialContainerRefProxyInfo(spatialId, spatialContainerRefProxy) {
50
- this.spatialId2ContainerRefProxy[spatialId] = spatialContainerRefProxy;
51
- }
52
- getSpatialContainerRefProxyBySpatialId(spatialId) {
53
- return this.spatialId2ContainerRefProxy[spatialId];
54
- }
55
- // notify when TransformVisibilityTaskContainer data change
56
- fnsForSpatialTransformVisibility = {};
57
- // used by StandardSpatializedContainer and PortalSpatializedContainer
58
- onSpatialTransformVisibilityChange(spatialId, fn) {
59
- if (!this.fnsForSpatialTransformVisibility[spatialId]) {
60
- this.fnsForSpatialTransformVisibility[spatialId] = [];
61
- }
62
- this.fnsForSpatialTransformVisibility[spatialId].push(fn);
63
- if (this.spatialId2transformVisibility[spatialId]) {
64
- fn(this.spatialId2transformVisibility[spatialId]);
65
- }
66
- }
67
- offSpatialTransformVisibilityChange(spatialId, fn) {
68
- const fns = this.fnsForSpatialTransformVisibility[spatialId];
69
- if (fns) {
70
- this.fnsForSpatialTransformVisibility[spatialId] = fns.filter(
71
- (f) => f !== fn
72
- );
73
- }
74
- }
75
- on2DFrameChange(spatialId, fn) {
76
- this.fns[spatialId] = fn;
77
- if (this.dom) {
78
- fn();
79
- }
80
- }
81
- off2DFrameChange(spatialId) {
82
- delete this.fns[spatialId];
83
- delete this.spatialId2dom[spatialId];
84
- delete this.spatialId2parentSpatialDom[spatialId];
85
- }
86
- querySpatialDomBySpatialId(spatialId) {
87
- if (this.domSpatialId === spatialId) {
88
- return this.dom;
89
- }
90
- if (!this.dom) {
91
- return null;
92
- }
93
- if (!this.spatialId2dom[spatialId]) {
94
- const spatialDom = this.dom.querySelector(`[${SpatialID}="${spatialId}"]`);
95
- if (spatialDom) {
96
- this.spatialId2dom[spatialId] = spatialDom;
97
- }
98
- }
99
- return this.spatialId2dom[spatialId];
100
- }
101
- queryParentSpatialDomBySpatialId(spatialId) {
102
- if (this.domSpatialId === spatialId) {
103
- return null;
104
- }
105
- if (this.spatialId2parentSpatialDom[spatialId]) {
106
- return this.spatialId2parentSpatialDom[spatialId];
107
- }
108
- let spatialDom = this.querySpatialDomBySpatialId(spatialId);
109
- if (spatialDom) {
110
- if (spatialDom === this.dom) return null;
111
- let parentSpatialDom = spatialDom.parentElement;
112
- while (parentSpatialDom && spatialDom !== this.dom) {
113
- if (parentSpatialDom.hasAttribute(SpatialID)) {
114
- break;
115
- } else {
116
- parentSpatialDom = parentSpatialDom.parentElement;
117
- }
118
- }
119
- this.spatialId2parentSpatialDom[spatialId] = parentSpatialDom;
120
- return parentSpatialDom;
121
- }
122
- return null;
123
- }
124
- getSpatialId(layer, isInStandardInstance, name = "") {
125
- if (this.layerSequences[layer] === void 0) {
126
- this.layerSequences[layer] = [0, 0];
127
- }
128
- const idx = isInStandardInstance ? 0 : 1;
129
- const sequenceId = this.layerSequences[layer][idx];
130
- this.layerSequences[layer][idx] = sequenceId + 1;
131
- const spatialId = `${name}_${layer}_${sequenceId}`;
132
- return spatialId;
133
- }
134
- };
135
- var SpatializedContainerContext = createContext(null);
136
-
137
- // src/spatialized-container/hooks/use2DFrameDetector.ts
138
- function use2DFrameDetector(ref) {
139
- const spatializedContainerObject = useContext(
140
- SpatializedContainerContext
141
- );
142
- const notify2DFrameChange = useCallback(() => {
143
- ref.current && spatializedContainerObject.notify2DFramePlaceHolderChange(ref.current);
144
- }, [ref.current, spatializedContainerObject]);
145
- useLayoutEffect(notify2DFrameChange, [notify2DFrameChange]);
146
- useEffect(() => {
147
- if (!ref.current || !spatializedContainerObject) {
148
- console.warn(
149
- "Ref is not attached to the DOM or spatializedContainerObject is not available"
150
- );
151
- return;
152
- }
153
- window.addEventListener("resize", notify2DFrameChange);
154
- return () => {
155
- window.removeEventListener("resize", notify2DFrameChange);
156
- };
157
- }, []);
158
- useEffect(() => {
159
- if (!ref.current) {
160
- console.warn("Ref is not attached to the DOM");
161
- return;
162
- }
163
- const ro = new ResizeObserver(notify2DFrameChange);
164
- ro.observe(ref.current);
165
- return () => {
166
- ro.disconnect();
167
- };
168
- }, []);
169
- useEffect(() => {
170
- if (!ref.current) {
171
- console.warn("Ref is not attached to the DOM");
172
- return;
173
- }
174
- const ro = new MutationObserver(notify2DFrameChange);
175
- ro.observe(ref.current, {
176
- attributeFilter: ["class", "style"],
177
- subtree: true
178
- });
179
- return () => {
180
- ro.disconnect();
181
- };
182
- }, []);
183
- }
184
-
185
- // src/spatialized-container/StandardSpatializedContainer.tsx
186
- import {
187
- forwardRef,
188
- useCallback as useCallback2,
189
- useContext as useContext2,
190
- useEffect as useEffect2,
191
- useRef,
192
- useState
193
- } from "react";
194
- import { jsx } from "react/jsx-runtime";
195
- function useSpatialTransformVisibilityWatcher(spatialId) {
196
- const [transformExist, setTransformExist] = useState(false);
197
- const spatializedContainerObject = useContext2(SpatializedContainerContext);
198
- useEffect2(() => {
199
- const fn = (spatialTransform) => {
200
- setTransformExist(spatialTransform.transform !== "none");
201
- };
202
- spatializedContainerObject.onSpatialTransformVisibilityChange(spatialId, fn);
203
- return () => {
204
- spatializedContainerObject.offSpatialTransformVisibilityChange(
205
- spatialId,
206
- fn
207
- );
208
- };
209
- }, [spatialId, spatializedContainerObject]);
210
- return transformExist;
211
- }
212
- function useInternalRef(ref) {
213
- const refInternal = useRef(null);
214
- const refInternalCallback = useCallback2(
215
- (node) => {
216
- refInternal.current = node;
217
- if (typeof ref === "function") {
218
- ref(node);
219
- } else if (ref) {
220
- ref.current = node;
221
- }
222
- },
223
- [ref]
224
- );
225
- return { refInternal, refInternalCallback };
226
- }
227
- function StandardSpatializedContainerBase(props, ref) {
228
- const {
229
- component: Component,
230
- style: inStyle = {},
231
- className,
232
- inStandardSpatializedContainer = false,
233
- ...restProps
234
- } = props;
235
- const { refInternal, refInternalCallback } = useInternalRef(ref);
236
- if (!inStandardSpatializedContainer) {
237
- use2DFrameDetector(refInternal);
238
- }
239
- const transformExist = useSpatialTransformVisibilityWatcher(props[SpatialID]);
240
- const classNames = className ? `${className} xr-spatial-default` : "xr-spatial-default";
241
- return /* @__PURE__ */ jsx(
242
- Component,
243
- {
244
- ref: refInternalCallback,
245
- style: inStyle,
246
- className: classNames,
247
- ...restProps,
248
- "data-xr-host": "",
249
- "data-xr-transform-active": transformExist ? "" : void 0
250
- }
251
- );
252
- }
253
- var StandardSpatializedContainer = forwardRef(
254
- StandardSpatializedContainerBase
255
- );
256
- var SPATIAL_DEFAULT_STYLE_CSS = `
257
- :where(.xr-spatial-default) {
258
- --xr-back: 0;
259
- --xr-depth: 0;
260
- --xr-z-index: 0;
261
- --xr-background-material: none;
262
- }
263
- .xr-spatial-default[data-xr-host] {
264
- visibility: hidden !important;
265
- transition: none !important;
266
- transform: none !important;
267
- }
268
- .xr-spatial-default[data-xr-host][data-xr-transform-active] {
269
- transform: translateZ(0) !important;
270
- }
271
- `;
272
- var SPATIAL_DEFAULT_STYLE_MARKER = "data-xr-spatial-default-style";
273
- function ensureSpatialDefaultStyleInRoot(root) {
274
- const queryRoot = root === document ? document.head : root;
275
- if (queryRoot.querySelector(`style[${SPATIAL_DEFAULT_STYLE_MARKER}]`)) {
276
- return;
277
- }
278
- const ownerDoc = root === document ? document : root.ownerDocument || document;
279
- const styleElement = ownerDoc.createElement("style");
280
- styleElement.type = "text/css";
281
- styleElement.setAttribute(SPATIAL_DEFAULT_STYLE_MARKER, "");
282
- styleElement.innerHTML = SPATIAL_DEFAULT_STYLE_CSS;
283
- if (root === document) {
284
- document.head.appendChild(styleElement);
285
- } else {
286
- ;
287
- root.appendChild(styleElement);
288
- }
289
- }
290
- function injectSpatialDefaultStyle() {
291
- ensureSpatialDefaultStyleInRoot(document);
292
- }
293
-
294
- // src/spatialized-container/TransformVisibilityTaskContainer.tsx
295
- import {
296
- forwardRef as forwardRef2,
297
- useCallback as useCallback4,
298
- useRef as useRef2
299
- } from "react";
300
- import { createPortal } from "react-dom";
301
-
302
- // src/spatialized-container/hooks/useSpatialTransformVisibility.ts
303
- import { useCallback as useCallback3, useContext as useContext3, useEffect as useEffect3 } from "react";
304
-
305
- // src/notifyUpdateStandInstanceLayout.ts
306
- function notifyUpdateStandInstanceLayout() {
307
- document.dispatchEvent(
308
- new CustomEvent("standInstanceLayout" /* standInstanceLayout */, {
309
- detail: {}
310
- })
311
- );
312
- }
313
- function notifyDOMUpdate(mutationsList) {
314
- document.dispatchEvent(
315
- new CustomEvent("domUpdated" /* domUpdated */, {
316
- detail: mutationsList
317
- })
318
- );
319
- }
320
-
321
- // src/spatialized-container/hooks/useSpatialTransformVisibility.ts
322
- function parseTransformAndVisibilityProperties(node) {
323
- const computedStyle = getComputedStyle(node);
324
- const transform = computedStyle.getPropertyValue("transform");
325
- const visibility = computedStyle.getPropertyValue("visibility");
326
- return {
327
- visibility,
328
- transform
329
- };
330
- }
331
- function useSpatialTransformVisibility(spatialId, ref) {
332
- const spatializedContainerObject = useContext3(SpatializedContainerContext);
333
- const checkSpatialStyleUpdate = useCallback3(() => {
334
- if (!ref.current) {
335
- return;
336
- }
337
- const spatialTransformVisibility = parseTransformAndVisibilityProperties(
338
- ref.current
339
- );
340
- spatializedContainerObject.updateSpatialTransformVisibility(
341
- spatialId,
342
- spatialTransformVisibility
343
- );
344
- }, []);
345
- useEffect3(() => {
346
- checkSpatialStyleUpdate();
347
- }, [checkSpatialStyleUpdate]);
348
- useEffect3(() => {
349
- const observer = new MutationObserver((mutationsList) => {
350
- checkSpatialStyleUpdate();
351
- });
352
- const config = {
353
- childList: false,
354
- subtree: false,
355
- attributes: true,
356
- // attributeOldValue: true,
357
- attributeFilter: ["style", "class"]
358
- };
359
- observer.observe(ref.current, config);
360
- return () => {
361
- observer.disconnect();
362
- };
363
- }, []);
364
- useEffect3(() => {
365
- const headObserver = new MutationObserver((mutations) => {
366
- checkSpatialStyleUpdate();
367
- });
368
- headObserver.observe(document.head, { childList: true, subtree: true });
369
- return () => {
370
- headObserver.disconnect();
371
- };
372
- }, []);
373
- useEffect3(() => {
374
- const onDomUpdated = (event) => {
375
- checkSpatialStyleUpdate();
376
- };
377
- document.addEventListener(
378
- "domUpdated" /* domUpdated */,
379
- onDomUpdated
380
- );
381
- return () => {
382
- document.removeEventListener(
383
- "domUpdated" /* domUpdated */,
384
- onDomUpdated
385
- );
386
- };
387
- }, []);
388
- }
389
-
390
- // src/spatialized-container/TransformVisibilityTaskContainer.tsx
391
- import { jsx as jsx2 } from "react/jsx-runtime";
392
- var cssParserDivContainer = null;
393
- function initCSSParserDivContainer() {
394
- cssParserDivContainer = document?.createElement("div");
395
- if (cssParserDivContainer) {
396
- cssParserDivContainer.style.position = "absolute";
397
- cssParserDivContainer.setAttribute("data-id", "css-parser-div-container");
398
- }
399
- }
400
- function createOrGetCSSParserDivContainer() {
401
- if (cssParserDivContainer && !cssParserDivContainer.parentElement) {
402
- document?.body.appendChild(cssParserDivContainer);
403
- }
404
- return cssParserDivContainer;
405
- }
406
- function useInternalRef2(ref) {
407
- const refInternal = useRef2(null);
408
- const refInternalCallback = useCallback4(
409
- (node) => {
410
- refInternal.current = node;
411
- if (typeof ref === "function") {
412
- ref(node);
413
- } else if (ref) {
414
- ref.current = node;
415
- }
416
- },
417
- [ref]
418
- );
419
- return { refInternal, refInternalCallback };
420
- }
421
- function TransformVisibilityTaskContainerBase(props, ref) {
422
- const { style: inStyle, ...restProps } = props;
423
- const extraStyle = {
424
- // when width/height equal to zero, transform: translateX(-50%) won't work
425
- // to make sure the element is not visible, we set left/top to a very large negative value
426
- left: -1e4,
427
- top: -1e4,
428
- pointerEvents: "none",
429
- opacity: 0,
430
- // width: 0,
431
- // height: 0,
432
- padding: 0,
433
- transition: "none",
434
- position: "absolute"
435
- };
436
- const { refInternal, refInternalCallback } = useInternalRef2(ref);
437
- const style = { ...inStyle, ...extraStyle };
438
- useSpatialTransformVisibility(props[SpatialID], refInternal);
439
- const cssParserDivContainer2 = createOrGetCSSParserDivContainer();
440
- if (!cssParserDivContainer2) {
441
- return null;
442
- }
443
- return createPortal(
444
- /* @__PURE__ */ jsx2("div", { ref: refInternalCallback, style, ...restProps }),
445
- cssParserDivContainer2
446
- );
447
- }
448
- var TransformVisibilityTaskContainer = forwardRef2(
449
- TransformVisibilityTaskContainerBase
450
- );
451
-
452
- // src/spatialized-container/SpatializedContainer.tsx
453
- import {
454
- forwardRef as forwardRef4,
455
- useCallback as useCallback6,
456
- useContext as useContext7,
457
- useEffect as useEffect10,
458
- useLayoutEffect as useLayoutEffect2,
459
- useMemo as useMemo2,
460
- useRef as useRef5,
461
- useState as useState6
462
- } from "react";
463
-
464
- // src/noRuntime.ts
465
- function supports(name, _tokens) {
466
- if (name === "useMetrics" || name === "convertCoordinate") {
467
- return true;
468
- }
469
- return false;
470
- }
471
- var WebSpatialRuntimeError = class extends Error {
472
- capability;
473
- constructor(capability, message) {
474
- super(
475
- message ?? `Capability "${capability}" is not supported in this WebSpatial runtime`
476
- );
477
- this.name = "WebSpatialRuntimeError";
478
- this.capability = capability;
479
- }
480
- };
481
- var Spatial = class {
482
- /**
483
- * Requests a session object from the browser
484
- * @returns The session or null if not available in the current browser
485
- * [TODO] discuss implications of this not being async
486
- */
487
- requestSession() {
488
- return null;
489
- }
490
- /**
491
- * Checks if the current page is running in a spatial web environment.
492
- * This method detects if the application is running in a WebSpatial-compatible browser.
493
- * @returns True if running in a spatial web environment, false otherwise
494
- */
495
- runInSpatialWeb() {
496
- return false;
497
- }
498
- /**
499
- * @returns true if web spatial is supported by this webpage
500
- */
501
- isSupported() {
502
- return false;
503
- }
504
- /**
505
- * Gets the native version, format is "x.x.x"
506
- * @returns native version string, or null when runtime is unavailable
507
- */
508
- getNativeVersion() {
509
- return null;
510
- }
511
- /**
512
- * Gets the client version, format is "x.x.x"
513
- * @returns client version string, or null when runtime is unavailable
514
- */
515
- getClientVersion() {
516
- return null;
517
- }
518
- };
519
- function isSSREnv() {
520
- return false;
521
- }
522
- var PhysicalMetrics = {
523
- pointToPhysical: (point, options) => {
524
- return point / 1360;
525
- },
526
- physicalToPoint: (physical, options) => {
527
- return physical * 1360;
528
- },
529
- getValue: () => ({
530
- meterToPtUnscaled: 1360,
531
- meterToPtScaled: 1360
532
- }),
533
- subscribe: (cb) => () => {
534
- }
535
- };
536
-
537
- // src/utils/getSession.ts
538
- var spatial = null;
539
- var _currentSession = null;
540
- function getSession() {
541
- if (isSSREnv()) return null;
542
- if (!spatial) {
543
- spatial = new Spatial();
544
- }
545
- if (!spatial.isSupported()) {
546
- return null;
547
- }
548
- if (_currentSession) {
549
- return _currentSession;
550
- }
551
- _currentSession = spatial.requestSession();
552
- return _currentSession;
553
- }
554
-
555
- // src/spatialized-container/context/SpatialLayerContext.ts
556
- import { createContext as createContext2 } from "react";
557
- var SpatialLayerContext = createContext2(0);
558
-
559
- // src/spatialized-container/PortalSpatializedContainer.tsx
560
- import { useMemo, useContext as useContext4, useEffect as useEffect6 } from "react";
561
-
562
- // src/spatialized-container/context/PortalInstanceContext.ts
563
- import { createContext as createContext3 } from "react";
564
-
565
- // src/spatialized-container/utils.ts
566
- function getInheritedStyleProps(computedStyle) {
567
- var propNames = [
568
- "azimuth",
569
- "borderCollapse",
570
- "borderSpacing",
571
- "captionSide",
572
- "color",
573
- "cursor",
574
- "direction",
575
- // 'elevation',
576
- "emptyCells",
577
- "fontFamily",
578
- "fontSize",
579
- "fontStyle",
580
- "fontVariant",
581
- "fontWeight",
582
- "font",
583
- "letterSpacing",
584
- "lineHeight",
585
- "listStyleImage",
586
- "listStylePosition",
587
- "listStyleType",
588
- "listStyle",
589
- "orphans",
590
- // 'pitchRange',
591
- // 'pitch',
592
- "quotes",
593
- // 'richness',
594
- // 'speakHeader',
595
- // 'speakNumeral',
596
- // 'speakPunctuation',
597
- // 'speak',
598
- // 'speechRate',
599
- // 'stress',
600
- "textAlign",
601
- "textIndent",
602
- "textTransform",
603
- "visibility",
604
- // 'voiceFamily',
605
- // 'volume',
606
- "whiteSpace",
607
- "widows",
608
- "wordSpacing",
609
- // background also need to be synced
610
- "background",
611
- // position also need to be synced
612
- "position",
613
- "width",
614
- "height",
615
- "display",
616
- // content-visibility also need to be synced
617
- "contentVisibility"
618
- ];
619
- var props = {};
620
- for (var cssName of propNames) {
621
- if (computedStyle[cssName]) {
622
- props[cssName] = computedStyle[cssName];
623
- }
624
- }
625
- return props;
626
- }
627
- function parseTransformOrigin(computedStyle) {
628
- const transformOriginProperty = computedStyle.getPropertyValue("transform-origin");
629
- const [x, y] = transformOriginProperty.split(" ").map(parseFloat);
630
- const width = parseFloat(computedStyle.getPropertyValue("width"));
631
- const height = parseFloat(computedStyle.getPropertyValue("height"));
632
- return {
633
- x: width > 0 ? x / width : 0.5,
634
- y: height > 0 ? y / height : 0.5,
635
- z: 0.5
636
- };
637
- }
638
- function parseBorderRadius(borderProperty, width) {
639
- if (borderProperty === "") {
640
- return 0;
641
- }
642
- if (borderProperty.endsWith("%")) {
643
- return width * parseFloat(borderProperty) / 100;
644
- }
645
- return parseFloat(borderProperty);
646
- }
647
- function parseCornerRadius(computedStyle) {
648
- const width = parseFloat(computedStyle.getPropertyValue("width"));
649
- const topLeftPropertyValue = computedStyle.getPropertyValue(
650
- "border-top-left-radius"
651
- );
652
- const topRightPropertyValue = computedStyle.getPropertyValue(
653
- "border-top-right-radius"
654
- );
655
- const bottomLeftPropertyValue = computedStyle.getPropertyValue(
656
- "border-bottom-left-radius"
657
- );
658
- const bottomRightPropertyValue = computedStyle.getPropertyValue(
659
- "border-bottom-right-radius"
660
- );
661
- const cornerRadius = {
662
- topLeading: parseBorderRadius(topLeftPropertyValue, width),
663
- bottomLeading: parseBorderRadius(bottomLeftPropertyValue, width),
664
- topTrailing: parseBorderRadius(topRightPropertyValue, width),
665
- bottomTrailing: parseBorderRadius(bottomRightPropertyValue, width)
666
- };
667
- return cornerRadius;
668
- }
669
- function extractAndRemoveCustomProperties(cssText, properties) {
670
- if (!cssText) {
671
- return { extractedValues: {}, filteredCssText: "" };
672
- }
673
- const extractedValues = {};
674
- const rules = cssText.split(";");
675
- const filteredRules = rules.filter((rule) => {
676
- const [key, value] = rule.split(":").map((part) => part.trim());
677
- if (properties.includes(key)) {
678
- extractedValues[key] = value;
679
- return false;
680
- }
681
- return true;
682
- });
683
- const filteredCssText = filteredRules.join(";").trim();
684
- return { extractedValues, filteredCssText };
685
- }
686
- function joinToCSSText(cssKV) {
687
- const rules = Object.entries(cssKV).map(([key, value]) => `${key}: ${value}`);
688
- return rules.join(";");
689
- }
690
-
691
- // src/spatialized-container/types.ts
692
- var SpatialCustomStyleVars = {
693
- back: "--xr-back",
694
- depth: "--xr-depth",
695
- backgroundMaterial: "--xr-background-material",
696
- xrZIndex: "--xr-z-index"
697
- };
698
-
699
- // src/utils/debugTool.ts
700
- async function inspectCurrentSpatialScene() {
701
- const spatialScene = getSession().getSpatialScene();
702
- return spatialScene.inspect();
703
- }
704
- function getSpatialized2DElement(spatialized2DElement) {
705
- return spatialized2DElement.__innerSpatializedElement?.();
706
- }
707
- function enableDebugTool() {
708
- if (isSSREnv()) return;
709
- Object.assign(window, {
710
- inspectCurrentSpatialScene,
711
- getSpatialized2DElement
712
- });
713
- }
714
-
715
- // src/utils/urlUtils.ts
716
- function getAbsoluteUrl(url) {
717
- if (typeof window === "undefined" || !window.location?.href) {
718
- return url;
719
- }
720
- try {
721
- return new URL(url, window.location.href).href;
722
- } catch {
723
- return url;
724
- }
725
- }
726
-
727
- // src/spatialized-container/context/PortalInstanceContext.ts
728
- var PortalInstanceObject = class {
729
- spatialId;
730
- spatializedContainerObject;
731
- parentPortalInstanceObject;
732
- spatializedElement;
733
- // cachedDomInfo used for cache dom info
734
- // when dom is updated, this property should be updated as well
735
- cachedDomInfo;
736
- get dom() {
737
- return this.cachedDomInfo?.dom;
738
- }
739
- get computedStyle() {
740
- return this.cachedDomInfo?.computedStyle;
741
- }
742
- get isFixedPosition() {
743
- return this.cachedDomInfo?.isFixedPosition;
744
- }
745
- // cachedDomRect used for cache dom rect
746
- cachedDomRect;
747
- get domRect() {
748
- return this.cachedDomRect;
749
- }
750
- // cachedTransformVisibilityInfo used for cache transform visibility info
751
- cachedTransformVisibilityInfo;
752
- get transformMatrix() {
753
- return this.cachedTransformVisibilityInfo?.transformMatrix;
754
- }
755
- get visibility() {
756
- return this.cachedTransformVisibilityInfo?.visibility;
757
- }
758
- // spatializedElementPromise used for get spatialized element
759
- // SpatializedElement is when attachSpatializedElement is called
760
- spatializedElementPromise;
761
- spatializedElementResolver;
762
- // used for get extra spatialized element properties
763
- getExtraSpatializedElementProperties;
764
- constructor(spatialId, spatializedContainerObject, parentPortalInstanceObject, getExtraSpatializedElementProperties2) {
765
- this.spatialId = spatialId;
766
- this.spatializedContainerObject = spatializedContainerObject;
767
- this.parentPortalInstanceObject = parentPortalInstanceObject;
768
- this.getExtraSpatializedElementProperties = getExtraSpatializedElementProperties2;
769
- this.spatializedElementPromise = new Promise(
770
- (resolve) => {
771
- this.spatializedElementResolver = resolve;
772
- }
773
- );
774
- }
775
- // called when PortalSpatializedContainer is mounted
776
- init() {
777
- this.spatializedContainerObject.onSpatialTransformVisibilityChange(
778
- this.spatialId,
779
- this.onSpatialTransformVisibilityChange
780
- );
781
- }
782
- // called when PortalSpatializedContainer is unmounted
783
- destroy() {
784
- this.spatializedContainerObject.offSpatialTransformVisibilityChange(
785
- this.spatialId,
786
- this.onSpatialTransformVisibilityChange
787
- );
788
- }
789
- onSpatialTransformVisibilityChange = (spatialTransform) => {
790
- this.cachedTransformVisibilityInfo = {
791
- transformMatrix: new DOMMatrix(spatialTransform.transform),
792
- visibility: spatialTransform.visibility
793
- };
794
- this.updateSpatializedElementProperties();
795
- };
796
- // called when 2D frame change
797
- notify2DFrameChange() {
798
- const dom = this.spatializedContainerObject.querySpatialDomBySpatialId(
799
- this.spatialId
800
- );
801
- if (!dom) {
802
- return;
803
- }
804
- const computedStyle = getComputedStyle(dom);
805
- this.cachedDomInfo = {
806
- dom,
807
- computedStyle,
808
- isFixedPosition: computedStyle.getPropertyValue("position") === "fixed"
809
- };
810
- this.updateSpatializedElementProperties();
811
- const __innerSpatializedElement = () => this.spatializedElement;
812
- Object.assign(dom, {
813
- __innerSpatializedElement
814
- });
815
- }
816
- async getSpatializedElement() {
817
- return this.spatializedElementPromise;
818
- }
819
- // called when SpatializedElement is created
820
- attachSpatializedElement(spatializedElement) {
821
- this.spatializedElement = spatializedElement;
822
- this.addToParent(spatializedElement);
823
- this.spatializedElementResolver?.(spatializedElement);
824
- this.updateSpatializedElementProperties();
825
- }
826
- inAddingToParent = false;
827
- async addToParent(spatializedElement) {
828
- if (this.inAddingToParent) {
829
- return;
830
- }
831
- this.inAddingToParent = true;
832
- if (this.isFixedPosition || !this.parentPortalInstanceObject) {
833
- var spatialScene = await getSession().getSpatialScene();
834
- await spatialScene.addSpatializedElement(spatializedElement);
835
- } else {
836
- const parentSpatialized2DElement = await this.parentPortalInstanceObject.getSpatializedElement();
837
- parentSpatialized2DElement.addSpatializedElement(spatializedElement);
838
- }
839
- this.inAddingToParent = false;
840
- }
841
- updateSpatializedElementProperties() {
842
- const dom = this.dom;
843
- const spatializedElement = this.spatializedElement;
844
- const visibility = this.visibility;
845
- if (!dom || !spatializedElement || !visibility || !this.transformMatrix) {
846
- return;
847
- }
848
- const computedStyle = this.computedStyle;
849
- const isFixedPosition = this.isFixedPosition;
850
- let domRect = dom.getBoundingClientRect();
851
- let { x, y } = domRect;
852
- if (!isFixedPosition) {
853
- const parentDom = this.spatializedContainerObject.queryParentSpatialDomBySpatialId(
854
- this.spatialId
855
- );
856
- if (parentDom) {
857
- const parentDomRect = parentDom.getBoundingClientRect();
858
- x -= parentDomRect.x;
859
- y -= parentDomRect.y;
860
- } else {
861
- x += window.scrollX;
862
- y += window.scrollY;
863
- }
864
- }
865
- this.cachedDomRect = {
866
- x: domRect.x,
867
- y: domRect.y,
868
- width: domRect.width,
869
- height: domRect.height
870
- };
871
- const width = domRect.width;
872
- const height = domRect.height;
873
- const opacity = parseFloat(computedStyle.getPropertyValue("opacity"));
874
- const scrollWithParent = !isFixedPosition;
875
- const display = computedStyle.getPropertyValue("display");
876
- const visible = visibility === "visible" && display !== "none";
877
- const zIndex = parseFloat(
878
- computedStyle.getPropertyValue(SpatialCustomStyleVars.xrZIndex)
879
- ) || 0;
880
- const backOffset = parseFloat(computedStyle.getPropertyValue(SpatialCustomStyleVars.back)) || 0;
881
- const depth = parseFloat(
882
- computedStyle.getPropertyValue(SpatialCustomStyleVars.depth)
883
- ) || 0;
884
- const rotationAnchor = parseTransformOrigin(computedStyle);
885
- const extraProperties = this.getExtraSpatializedElementProperties?.(computedStyle) || {};
886
- spatializedElement.updateProperties({
887
- clientX: x,
888
- clientY: y,
889
- width,
890
- height,
891
- depth,
892
- opacity,
893
- scrollWithParent,
894
- zIndex,
895
- visible,
896
- backOffset,
897
- rotationAnchor,
898
- ...extraProperties
899
- });
900
- spatializedElement.updateTransform(this.transformMatrix);
901
- Object.assign(this.dom, {
902
- __spatializedElement: spatializedElement
903
- });
904
- }
905
- };
906
- var PortalInstanceContext = createContext3(
907
- null
908
- );
909
-
910
- // src/spatialized-container/hooks/useSync2DFrame.ts
911
- import { useEffect as useEffect4, useState as useState2 } from "react";
912
- function useForceUpdate() {
913
- const [, setToggle] = useState2(false);
914
- return () => setToggle((toggle) => !toggle);
915
- }
916
- function useSync2DFrame(spatialId, portalInstanceObject, spatializedContainerObject) {
917
- const forceUpdate = useForceUpdate();
918
- useEffect4(() => {
919
- spatializedContainerObject.on2DFrameChange(spatialId, () => {
920
- portalInstanceObject.notify2DFrameChange();
921
- forceUpdate();
922
- });
923
- return () => {
924
- spatializedContainerObject.off2DFrameChange(spatialId);
925
- };
926
- }, []);
927
- }
928
-
929
- // src/spatialized-container/hooks/useSpatializedElement.ts
930
- import { useEffect as useEffect5, useRef as useRef3, useState as useState3 } from "react";
931
- function useSpatializedElement(createSpatializedElement2, portalInstanceObject) {
932
- const [spatializedElement, setSpatializedElement] = useState3();
933
- const elementRef = useRef3(void 0);
934
- useEffect5(() => {
935
- let isDestroyed = false;
936
- createSpatializedElement2().then(
937
- (inSpatializedElement) => {
938
- if (!inSpatializedElement) return;
939
- if (!isDestroyed) {
940
- elementRef.current = inSpatializedElement;
941
- portalInstanceObject.attachSpatializedElement(inSpatializedElement);
942
- setSpatializedElement(inSpatializedElement);
943
- } else {
944
- inSpatializedElement?.destroy();
945
- }
946
- }
947
- );
948
- return () => {
949
- isDestroyed = true;
950
- const el = elementRef.current;
951
- if (el) {
952
- el.destroy();
953
- elementRef.current = void 0;
954
- setSpatializedElement(void 0);
955
- }
956
- };
957
- }, [createSpatializedElement2, portalInstanceObject]);
958
- return spatializedElement;
959
- }
960
-
961
- // src/spatialized-container/PortalSpatializedContainer.tsx
962
- import { Fragment, jsx as jsx3, jsxs } from "react/jsx-runtime";
963
- function constrainedAxisToVec3(input) {
964
- if (input == null) return { x: 0, y: 0, z: 0 };
965
- if (Array.isArray(input)) {
966
- return { x: input[0] ?? 0, y: input[1] ?? 0, z: input[2] ?? 0 };
967
- }
968
- const v = input;
969
- return { x: v.x, y: v.y, z: v.z };
970
- }
971
- function constrainedAxisKey(input) {
972
- const v = constrainedAxisToVec3(input);
973
- return `${v.x},${v.y},${v.z}`;
974
- }
975
- function renderPlaceholderInSubPortal(portalInstanceObject, El) {
976
- const spatialId = portalInstanceObject.spatialId;
977
- const inPortalInstanceEnv = !!portalInstanceObject.parentPortalInstanceObject;
978
- const position = portalInstanceObject.computedStyle?.getPropertyValue("position");
979
- const shouldRenderPlaceHolder = inPortalInstanceEnv && portalInstanceObject && portalInstanceObject.domRect && position !== "absolute" && position !== "fixed";
980
- if (!shouldRenderPlaceHolder) {
981
- return /* @__PURE__ */ jsx3(Fragment, {});
982
- }
983
- const { width, height } = portalInstanceObject.domRect;
984
- const display = portalInstanceObject.computedStyle.getPropertyValue("display");
985
- const spatialIdProps = { [SpatialID]: spatialId };
986
- return /* @__PURE__ */ jsx3(
987
- El,
988
- {
989
- ...spatialIdProps,
990
- style: {
991
- position: "relative",
992
- width: `${width}px`,
993
- height: `${height}px`,
994
- visibility: "hidden",
995
- display
996
- }
997
- }
998
- );
999
- }
1000
- function PortalSpatializedContainer(props) {
1001
- const {
1002
- spatializedContent: Content,
1003
- createSpatializedElement: createSpatializedElement2,
1004
- getExtraSpatializedElementProperties: getExtraSpatializedElementProperties2,
1005
- onSpatialTap,
1006
- onSpatialDragStart,
1007
- onSpatialDrag,
1008
- onSpatialDragEnd,
1009
- onSpatialRotate,
1010
- onSpatialRotateEnd,
1011
- onSpatialMagnify,
1012
- onSpatialMagnifyEnd,
1013
- spatialEventOptions,
1014
- [SpatialID]: spatialId,
1015
- ...restProps
1016
- } = props;
1017
- const spatializedContainerObject = useContext4(
1018
- SpatializedContainerContext
1019
- );
1020
- const parentPortalInstanceObject = useContext4(PortalInstanceContext);
1021
- const portalInstanceObject = useMemo(
1022
- () => new PortalInstanceObject(
1023
- spatialId,
1024
- spatializedContainerObject,
1025
- parentPortalInstanceObject,
1026
- getExtraSpatializedElementProperties2
1027
- ),
1028
- []
1029
- );
1030
- useEffect6(() => {
1031
- portalInstanceObject.init();
1032
- return () => {
1033
- portalInstanceObject.destroy();
1034
- };
1035
- }, []);
1036
- useSync2DFrame(spatialId, portalInstanceObject, spatializedContainerObject);
1037
- const spatializedElement = useSpatializedElement(
1038
- createSpatializedElement2,
1039
- portalInstanceObject
1040
- );
1041
- const PlaceholderEl = renderPlaceholderInSubPortal(
1042
- portalInstanceObject,
1043
- props.component
1044
- );
1045
- useEffect6(() => {
1046
- if (spatializedElement) {
1047
- spatializedElement.onSpatialTap = onSpatialTap;
1048
- }
1049
- }, [spatializedElement, onSpatialTap]);
1050
- useEffect6(() => {
1051
- if (spatializedElement) {
1052
- spatializedElement.onSpatialDrag = onSpatialDrag;
1053
- }
1054
- }, [spatializedElement, onSpatialDrag]);
1055
- useEffect6(() => {
1056
- if (spatializedElement) {
1057
- spatializedElement.onSpatialDragEnd = onSpatialDragEnd;
1058
- }
1059
- }, [spatializedElement, onSpatialDragEnd]);
1060
- useEffect6(() => {
1061
- if (spatializedElement) {
1062
- spatializedElement.onSpatialRotate = onSpatialRotate;
1063
- }
1064
- }, [spatializedElement, onSpatialRotate]);
1065
- useEffect6(() => {
1066
- if (spatializedElement) {
1067
- spatializedElement.onSpatialRotateEnd = onSpatialRotateEnd;
1068
- }
1069
- }, [spatializedElement, onSpatialRotateEnd]);
1070
- useEffect6(() => {
1071
- if (spatializedElement) {
1072
- spatializedElement.onSpatialMagnify = onSpatialMagnify;
1073
- }
1074
- }, [spatializedElement, onSpatialMagnify]);
1075
- useEffect6(() => {
1076
- if (spatializedElement) {
1077
- spatializedElement.onSpatialMagnifyEnd = onSpatialMagnifyEnd;
1078
- }
1079
- }, [spatializedElement, onSpatialMagnifyEnd]);
1080
- useEffect6(() => {
1081
- if (spatializedElement) {
1082
- spatializedElement.onSpatialDragStart = onSpatialDragStart;
1083
- }
1084
- }, [spatializedElement, onSpatialDragStart]);
1085
- const rotateConstraintKey = constrainedAxisKey(
1086
- spatialEventOptions?.constrainedToAxis
1087
- );
1088
- useEffect6(() => {
1089
- if (!spatializedElement) return;
1090
- const axis = constrainedAxisToVec3(spatialEventOptions?.constrainedToAxis);
1091
- void spatializedElement.updateProperties({ rotateConstrainedToAxis: axis });
1092
- }, [spatializedElement, rotateConstraintKey]);
1093
- return /* @__PURE__ */ jsxs(PortalInstanceContext.Provider, { value: portalInstanceObject, children: [
1094
- spatializedElement && portalInstanceObject.dom && /* @__PURE__ */ jsx3(Content, { spatializedElement, ...restProps }),
1095
- PlaceholderEl
1096
- ] });
1097
- }
1098
-
1099
- // src/spatialized-container/hooks/useDomProxy.ts
1100
- import { useCallback as useCallback5, useEffect as useEffect7, useRef as useRef4 } from "react";
1101
- var SpatialContainerRefProxy = class {
1102
- transformVisibilityTaskContainerDom = null;
1103
- /** Raw Standard host element (styled root). Used to mirror class onto the transform probe. */
1104
- standardRawDom = null;
1105
- standardClassObserver = null;
1106
- /**
1107
- * When set, Standard's DOM className is forwarded here so TransformVisibilityTaskContainer
1108
- * can render it from React state (avoids React clobbering imperative class updates).
1109
- */
1110
- mirrorClassNotify = null;
1111
- /** Last class string applied to the probe + used to skip redundant syncs. */
1112
- lastMirroredClassName = null;
1113
- /** Coalesce multiple class sync triggers in the same turn (Observer + classList, etc.). */
1114
- classSyncMicrotaskQueued = false;
1115
- ref;
1116
- domProxy;
1117
- /** Last value dispatched to `ref` (undefined = none yet); avoids duplicate null/proxy writes. */
1118
- lastOutgoingToRef = void 0;
1119
- installedProperties = [];
1120
- // extre ref props, used to add extra props to ref
1121
- extraRefProps;
1122
- constructor(ref, extraRefProps) {
1123
- this.ref = ref;
1124
- this.extraRefProps = extraRefProps;
1125
- }
1126
- setMirrorClassNotify(fn) {
1127
- this.mirrorClassNotify = fn;
1128
- if (fn && this.standardRawDom) {
1129
- this.flushSyncTransformClassFromStandard(true);
1130
- }
1131
- }
1132
- disconnectStandardClassObserver() {
1133
- this.standardClassObserver?.disconnect();
1134
- this.standardClassObserver = null;
1135
- }
1136
- attachStandardClassObserver() {
1137
- this.disconnectStandardClassObserver();
1138
- if (!this.standardRawDom) {
1139
- return;
1140
- }
1141
- this.standardClassObserver = new MutationObserver(() => {
1142
- this.ensureSpatialDefaultClass();
1143
- this.scheduleSyncTransformClassFromStandard();
1144
- });
1145
- this.standardClassObserver.observe(this.standardRawDom, {
1146
- attributes: true,
1147
- attributeFilter: ["class"]
1148
- });
1149
- }
1150
- ensureSpatialDefaultClass() {
1151
- const dom = this.standardRawDom;
1152
- if (!dom) return;
1153
- if (dom.classList.contains("xr-spatial-default")) return;
1154
- dom.classList.add("xr-spatial-default");
1155
- }
1156
- /**
1157
- * Merge multiple sync requests (e.g. classList hook + MutationObserver) into one microtask.
1158
- */
1159
- scheduleSyncTransformClassFromStandard() {
1160
- if (this.classSyncMicrotaskQueued) {
1161
- return;
1162
- }
1163
- this.classSyncMicrotaskQueued = true;
1164
- queueMicrotask(() => {
1165
- this.classSyncMicrotaskQueued = false;
1166
- this.flushSyncTransformClassFromStandard(false);
1167
- });
1168
- }
1169
- /**
1170
- * Source of truth: Standard host DOM (incl. styled-components runtime class changes).
1171
- * @param force when true, skip same-string short-circuit (e.g. mirror notify just registered).
1172
- */
1173
- flushSyncTransformClassFromStandard(force) {
1174
- if (!this.standardRawDom) {
1175
- return;
1176
- }
1177
- const name = this.standardRawDom.className;
1178
- const probe = this.transformVisibilityTaskContainerDom;
1179
- if (!force && probe && probe.className === name && this.lastMirroredClassName === name) {
1180
- return;
1181
- }
1182
- this.lastMirroredClassName = name;
1183
- if (probe) {
1184
- probe.className = name;
1185
- }
1186
- this.mirrorClassNotify?.(name);
1187
- }
1188
- updateStandardSpatializedContainerDom(dom) {
1189
- if (!dom) {
1190
- this.disconnectStandardClassObserver();
1191
- this.clearInstalledProperties();
1192
- this.standardRawDom = null;
1193
- this.lastMirroredClassName = null;
1194
- this.domProxy = void 0;
1195
- this.updateDomProxyToRef();
1196
- return;
1197
- }
1198
- if (this.standardRawDom === dom && this.domProxy) {
1199
- this.scheduleSyncTransformClassFromStandard();
1200
- return;
1201
- }
1202
- this.clearInstalledProperties();
1203
- this.standardRawDom = dom;
1204
- this.domProxy = dom;
1205
- this.installSpatialRefBehavior(dom);
1206
- const root = dom.getRootNode();
1207
- if (root === document || root instanceof ShadowRoot) {
1208
- ensureSpatialDefaultStyleInRoot(root);
1209
- }
1210
- this.attachStandardClassObserver();
1211
- this.updateDomProxyToRef();
1212
- this.scheduleSyncTransformClassFromStandard();
1213
- }
1214
- clearInstalledProperties() {
1215
- const dom = this.standardRawDom;
1216
- if (!dom) return;
1217
- for (const prop of this.installedProperties) {
1218
- delete dom[prop];
1219
- }
1220
- this.installedProperties = [];
1221
- }
1222
- defineDomProperty(dom, prop, descriptor) {
1223
- Object.defineProperty(dom, prop, {
1224
- configurable: true,
1225
- ...descriptor
1226
- });
1227
- this.installedProperties.push(prop);
1228
- }
1229
- installSpatialRefBehavior(dom) {
1230
- const self = this;
1231
- const rawStyle = dom.style;
1232
- const rawRemoveProperty = rawStyle.removeProperty.bind(rawStyle);
1233
- const rawGetPropertyValue = rawStyle.getPropertyValue.bind(rawStyle);
1234
- const rawRemoveAttribute = dom.removeAttribute.bind(dom);
1235
- const spatialStyleProperties = ["visibility", "transform"];
1236
- const styleProxy = new Proxy(rawStyle, {
1237
- get(target, prop) {
1238
- if (prop === "visibility" || prop === "transform") {
1239
- return self.transformVisibilityTaskContainerDom?.style.getPropertyValue(
1240
- prop
1241
- );
1242
- }
1243
- const value = Reflect.get(target, prop);
1244
- if (typeof value === "function") {
1245
- if (prop === "setProperty" || prop === "removeProperty" || prop === "getPropertyValue") {
1246
- return function(...args) {
1247
- const [property] = args;
1248
- if (spatialStyleProperties.includes(property)) {
1249
- if (prop === "setProperty") {
1250
- const [, kValue, priority] = args;
1251
- self.transformVisibilityTaskContainerDom?.style.setProperty(
1252
- property,
1253
- kValue,
1254
- priority
1255
- );
1256
- } else if (prop === "removeProperty") {
1257
- return self.transformVisibilityTaskContainerDom?.style.removeProperty(
1258
- property
1259
- );
1260
- } else if (prop === "getPropertyValue") {
1261
- return self.transformVisibilityTaskContainerDom?.style.getPropertyValue(
1262
- property
1263
- );
1264
- }
1265
- return void 0;
1266
- }
1267
- return value.apply(this, args);
1268
- }.bind(target);
1269
- }
1270
- return value.bind(target);
1271
- }
1272
- return value;
1273
- },
1274
- set(target, prop, value) {
1275
- if (prop === "visibility") {
1276
- self.transformVisibilityTaskContainerDom?.style.setProperty(
1277
- "visibility",
1278
- value
1279
- );
1280
- return true;
1281
- }
1282
- if (prop === "transform") {
1283
- self.transformVisibilityTaskContainerDom?.style.setProperty(
1284
- "transform",
1285
- value
1286
- );
1287
- return true;
1288
- }
1289
- if (Object.values(SpatialCustomStyleVars).includes(prop)) {
1290
- target.setProperty(prop, value);
1291
- return true;
1292
- }
1293
- if (prop === "cssText") {
1294
- const { extractedValues, filteredCssText } = extractAndRemoveCustomProperties(
1295
- value,
1296
- spatialStyleProperties
1297
- );
1298
- spatialStyleProperties.forEach((key) => {
1299
- if (extractedValues[key]) {
1300
- self.transformVisibilityTaskContainerDom?.style.setProperty(
1301
- key,
1302
- extractedValues[key]
1303
- );
1304
- } else {
1305
- rawRemoveProperty(key);
1306
- }
1307
- });
1308
- const appendedCSSText = joinToCSSText({
1309
- transform: "none",
1310
- visibility: "hidden"
1311
- });
1312
- return Reflect.set(
1313
- target,
1314
- prop,
1315
- [appendedCSSText, filteredCssText].join(";")
1316
- );
1317
- }
1318
- return Reflect.set(target, prop, value);
1319
- }
1320
- });
1321
- this.defineDomProperty(dom, "style", {
1322
- get() {
1323
- return styleProxy;
1324
- },
1325
- set(value) {
1326
- styleProxy.cssText = String(value);
1327
- }
1328
- });
1329
- this.defineDomProperty(dom, "className", {
1330
- get() {
1331
- return dom.getAttribute("class") ?? "";
1332
- },
1333
- set(value) {
1334
- dom.setAttribute("class", String(value));
1335
- if (!dom.classList.contains("xr-spatial-default")) {
1336
- dom.classList.add("xr-spatial-default");
1337
- }
1338
- self.scheduleSyncTransformClassFromStandard();
1339
- }
1340
- });
1341
- this.defineDomProperty(dom, "removeAttribute", {
1342
- value(property) {
1343
- if (property === "style") {
1344
- rawStyle.cssText = "visibility: hidden; transition: none; transform: none;";
1345
- self.transformVisibilityTaskContainerDom?.style.removeProperty(
1346
- "visibility"
1347
- );
1348
- self.transformVisibilityTaskContainerDom?.style.removeProperty(
1349
- "transform"
1350
- );
1351
- return;
1352
- }
1353
- if (property === "class") {
1354
- dom.className = "xr-spatial-default";
1355
- return;
1356
- }
1357
- return rawRemoveAttribute(property);
1358
- }
1359
- });
1360
- if (supports("xrClientDepth")) {
1361
- this.defineDomProperty(dom, "xrClientDepth", {
1362
- get() {
1363
- return rawGetPropertyValue(SpatialCustomStyleVars.depth);
1364
- }
1365
- });
1366
- }
1367
- if (supports("xrOffsetBack")) {
1368
- this.defineDomProperty(dom, "xrOffsetBack", {
1369
- get() {
1370
- return rawGetPropertyValue(SpatialCustomStyleVars.back);
1371
- }
1372
- });
1373
- }
1374
- if (this.extraRefProps) {
1375
- const extraProps = this.extraRefProps(dom);
1376
- for (const prop of Object.keys(extraProps)) {
1377
- this.defineDomProperty(dom, prop, {
1378
- get() {
1379
- return extraProps[prop];
1380
- },
1381
- set(value) {
1382
- extraProps[prop] = value;
1383
- }
1384
- });
1385
- }
1386
- }
1387
- }
1388
- updateTransformVisibilityTaskContainerDom(dom) {
1389
- this.transformVisibilityTaskContainerDom = dom;
1390
- if (!dom) {
1391
- this.lastMirroredClassName = null;
1392
- }
1393
- this.scheduleSyncTransformClassFromStandard();
1394
- this.updateDomProxyToRef();
1395
- }
1396
- updateDomProxyToRef() {
1397
- const ref = this.ref;
1398
- if (!ref) {
1399
- return;
1400
- }
1401
- const next = this.domProxy && this.transformVisibilityTaskContainerDom ? this.domProxy : null;
1402
- if (this.lastOutgoingToRef === next) {
1403
- return;
1404
- }
1405
- this.lastOutgoingToRef = next;
1406
- if (next) {
1407
- if (typeof ref === "function") {
1408
- ref(next);
1409
- } else {
1410
- ref.current = next;
1411
- }
1412
- } else {
1413
- if (typeof ref === "function") {
1414
- ref(null);
1415
- } else {
1416
- ref.current = null;
1417
- }
1418
- }
1419
- }
1420
- updateRef(ref) {
1421
- if (this.ref === ref) {
1422
- return;
1423
- }
1424
- this.ref = ref;
1425
- this.lastOutgoingToRef = void 0;
1426
- this.updateDomProxyToRef();
1427
- }
1428
- };
1429
- function useDomProxy(ref, extraRefProps) {
1430
- const spatialContainerRefProxy = useRef4(
1431
- new SpatialContainerRefProxy(ref, extraRefProps)
1432
- );
1433
- useEffect7(() => {
1434
- spatialContainerRefProxy.current.updateRef(ref);
1435
- }, [ref]);
1436
- const transformVisibilityTaskContainerCallback = useCallback5(
1437
- (el) => {
1438
- spatialContainerRefProxy.current.updateTransformVisibilityTaskContainerDom(
1439
- el
1440
- );
1441
- },
1442
- []
1443
- );
1444
- const standardSpatializedContainerCallback = useCallback5(
1445
- (el) => {
1446
- spatialContainerRefProxy.current.updateStandardSpatializedContainerDom(el);
1447
- },
1448
- []
1449
- );
1450
- return {
1451
- transformVisibilityTaskContainerCallback,
1452
- standardSpatializedContainerCallback,
1453
- spatialContainerRefProxy
1454
- };
1455
- }
1456
-
1457
- // src/reality/context/InsideAttachmentContext.tsx
1458
- import { createContext as createContext4, useContext as useContext5 } from "react";
1459
- var InsideAttachmentContext = createContext4(false);
1460
- var useInsideAttachment = () => useContext5(InsideAttachmentContext);
1461
-
1462
- // src/spatialized-container/hooks/useSpatialEvents.ts
1463
- function createEventProxy(event, currentTargetGetter, offsetXGetter, offsetYGetter, offsetZGetter, clientXGetter, clientYGetter, clientZGetter, translationXGetter, translationYGetter, translationZGetter, quaternionGetter, magnificationGetter) {
1464
- return new Proxy(event, {
1465
- get(target, prop) {
1466
- if (prop === "currentTarget") {
1467
- return currentTargetGetter();
1468
- }
1469
- if (prop === "isTrusted") {
1470
- return true;
1471
- }
1472
- if (prop === "bubbles") {
1473
- return false;
1474
- }
1475
- if (prop === "offsetX" && offsetXGetter) {
1476
- return offsetXGetter(target) ?? 0;
1477
- }
1478
- if (prop === "offsetY" && offsetYGetter) {
1479
- return offsetYGetter(target) ?? 0;
1480
- }
1481
- if (prop === "offsetZ" && offsetZGetter) {
1482
- return offsetZGetter(target) ?? 0;
1483
- }
1484
- if (prop === "clientX" && clientXGetter) {
1485
- return clientXGetter(target) ?? 0;
1486
- }
1487
- if (prop === "clientY" && clientYGetter) {
1488
- return clientYGetter(target) ?? 0;
1489
- }
1490
- if (prop === "clientZ" && clientZGetter) {
1491
- return clientZGetter(target) ?? 0;
1492
- }
1493
- if (prop === "translationX" && translationXGetter) {
1494
- return translationXGetter(target) ?? 0;
1495
- }
1496
- if (prop === "translationY" && translationYGetter) {
1497
- return translationYGetter(target) ?? 0;
1498
- }
1499
- if (prop === "translationZ" && translationZGetter) {
1500
- return translationZGetter(target) ?? 0;
1501
- }
1502
- if (prop === "quaternion" && quaternionGetter) {
1503
- return quaternionGetter(target) ?? { x: 0, y: 0, z: 0, w: 1 };
1504
- }
1505
- if (prop === "magnification" && magnificationGetter) {
1506
- return magnificationGetter(target) ?? 1;
1507
- }
1508
- return Reflect.get(target, prop);
1509
- }
1510
- });
1511
- }
1512
- function createEventHandler(handler, currentTargetGetter, offsetXGetter, offsetYGetter, offsetZGetter, clientXGetter, clientYGetter, clientZGetter, translationXGetter, translationYGetter, translationZGetter, quaternionGetter, magnificationGetter) {
1513
- return handler ? (event) => {
1514
- const proxyEvent = createEventProxy(
1515
- event,
1516
- currentTargetGetter,
1517
- offsetXGetter,
1518
- offsetYGetter,
1519
- offsetZGetter,
1520
- clientXGetter,
1521
- clientYGetter,
1522
- clientZGetter,
1523
- translationXGetter,
1524
- translationYGetter,
1525
- translationZGetter,
1526
- quaternionGetter,
1527
- magnificationGetter
1528
- );
1529
- handler(proxyEvent);
1530
- } : void 0;
1531
- }
1532
- function useSpatialEventsBase(spatialEvents, currentTargetGetter) {
1533
- const onSpatialTap = createEventHandler(
1534
- spatialEvents.onSpatialTap,
1535
- currentTargetGetter,
1536
- // offsetX/Y/Z come from local coordinates
1537
- (ev) => ev.detail?.location3D?.x,
1538
- (ev) => ev.detail?.location3D?.y,
1539
- (ev) => ev.detail?.location3D?.z,
1540
- // clientX/Y/Z come from global scene coordinates
1541
- (ev) => ev.detail?.globalLocation3D?.x,
1542
- (ev) => ev.detail?.globalLocation3D?.y,
1543
- (ev) => ev.detail?.globalLocation3D?.z
1544
- );
1545
- const onSpatialDrag = createEventHandler(
1546
- spatialEvents.onSpatialDrag,
1547
- currentTargetGetter,
1548
- void 0,
1549
- void 0,
1550
- void 0,
1551
- void 0,
1552
- void 0,
1553
- void 0,
1554
- (ev) => ev.detail?.translation3D?.x,
1555
- (ev) => ev.detail?.translation3D?.y,
1556
- (ev) => ev.detail?.translation3D?.z
1557
- );
1558
- const onSpatialDragEnd = createEventHandler(
1559
- spatialEvents.onSpatialDragEnd,
1560
- currentTargetGetter
1561
- );
1562
- const onSpatialRotate = createEventHandler(
1563
- spatialEvents.onSpatialRotate,
1564
- currentTargetGetter,
1565
- void 0,
1566
- void 0,
1567
- void 0,
1568
- void 0,
1569
- void 0,
1570
- void 0,
1571
- void 0,
1572
- void 0,
1573
- void 0,
1574
- (ev) => ev.detail?.quaternion
1575
- );
1576
- const onSpatialRotateEnd = createEventHandler(
1577
- spatialEvents.onSpatialRotateEnd,
1578
- currentTargetGetter
1579
- );
1580
- const onSpatialMagnify = createEventHandler(
1581
- spatialEvents.onSpatialMagnify,
1582
- currentTargetGetter,
1583
- void 0,
1584
- void 0,
1585
- void 0,
1586
- void 0,
1587
- void 0,
1588
- void 0,
1589
- void 0,
1590
- void 0,
1591
- void 0,
1592
- void 0,
1593
- (ev) => ev.detail?.magnification
1594
- );
1595
- const onSpatialMagnifyEnd = createEventHandler(
1596
- spatialEvents.onSpatialMagnifyEnd,
1597
- currentTargetGetter
1598
- );
1599
- const onSpatialDragStart = createEventHandler(
1600
- spatialEvents.onSpatialDragStart,
1601
- currentTargetGetter,
1602
- (ev) => ev.detail?.startLocation3D?.x,
1603
- (ev) => ev.detail?.startLocation3D?.y,
1604
- (ev) => ev.detail?.startLocation3D?.z,
1605
- (ev) => ev.detail?.globalLocation3D?.x,
1606
- (ev) => ev.detail?.globalLocation3D?.y,
1607
- (ev) => ev.detail?.globalLocation3D?.z
1608
- );
1609
- return {
1610
- onSpatialTap,
1611
- onSpatialDragStart,
1612
- onSpatialDrag,
1613
- onSpatialDragEnd,
1614
- onSpatialRotate,
1615
- onSpatialRotateEnd,
1616
- onSpatialMagnify,
1617
- onSpatialMagnifyEnd
1618
- };
1619
- }
1620
- function useSpatialEvents(spatialEvents, spatialContainerRefProxy) {
1621
- return useSpatialEventsBase(
1622
- spatialEvents,
1623
- () => spatialContainerRefProxy.current?.domProxy
1624
- );
1625
- }
1626
- function useSpatialEventsWhenSpatializedContainerExist(spatialEvents, spatialId, spatializedContainerObject) {
1627
- return useSpatialEventsBase(spatialEvents, () => {
1628
- const spatialContainerRefProxy = spatializedContainerObject.getSpatialContainerRefProxyBySpatialId(
1629
- spatialId
1630
- );
1631
- return spatialContainerRefProxy?.domProxy;
1632
- });
1633
- }
1634
-
1635
- // src/ssr/SSRContext.tsx
1636
- import { createContext as createContext5, useState as useState4, useEffect as useEffect8 } from "react";
1637
- import { jsx as jsx4 } from "react/jsx-runtime";
1638
- var SSRContext = createContext5(false);
1639
- var SSRProvider = ({
1640
- isSSR: initialIsSSR = true,
1641
- children
1642
- }) => {
1643
- const [isSSR, setIsSSR] = useState4(initialIsSSR);
1644
- useEffect8(() => {
1645
- if (isSSR) {
1646
- setIsSSR(false);
1647
- }
1648
- }, []);
1649
- return /* @__PURE__ */ jsx4(SSRContext.Provider, { value: isSSR, children });
1650
- };
1651
-
1652
- // src/ssr/withSSRSupported.tsx
1653
- import { forwardRef as forwardRef3 } from "react";
1654
-
1655
- // src/ssr/useSSRPhase.tsx
1656
- import { useContext as useContext6, useState as useState5, useEffect as useEffect9 } from "react";
1657
- function useSSRPhase() {
1658
- const isSSRContext = useContext6(SSRContext);
1659
- const isServer = typeof window === "undefined";
1660
- const [hydrated, setHydrated] = useState5(false);
1661
- useEffect9(() => setHydrated(true), []);
1662
- if (isServer) {
1663
- return "ssr";
1664
- }
1665
- if (isSSRContext) {
1666
- return hydrated ? "after-hydrate" : "hydrate";
1667
- } else {
1668
- return "after-hydrate";
1669
- }
1670
- }
1671
-
1672
- // src/ssr/withSSRSupported.tsx
1673
- import { jsx as jsx5 } from "react/jsx-runtime";
1674
- function withSSRSupported(Component) {
1675
- const ClientOnlyComponent = (props, ref) => {
1676
- const phase = useSSRPhase();
1677
- let renderType = "real";
1678
- if (phase === "ssr" || phase === "hydrate") {
1679
- renderType = "fake";
1680
- }
1681
- if (renderType === "fake") {
1682
- const { style, className } = props;
1683
- return /* @__PURE__ */ jsx5("div", { style, className, ref });
1684
- } else {
1685
- return /* @__PURE__ */ jsx5(Component, { ...props, ref });
1686
- }
1687
- };
1688
- ClientOnlyComponent.displayName = `withClientOnly(${Component.displayName || Component.name || "Component"})`;
1689
- return forwardRef3(ClientOnlyComponent);
1690
- }
1691
-
1692
- // src/spatialized-container/SpatializedContainer.tsx
1693
- import { jsx as jsx6, jsxs as jsxs2 } from "react/jsx-runtime";
1694
- function DegradedContainer({
1695
- innerRef,
1696
- enableOnSpatialContentReadyFallback,
1697
- ...inprops
1698
- }) {
1699
- const {
1700
- component: Component,
1701
- children,
1702
- ["enable-xr"]: _enableXR,
1703
- onSpatialTap: _onSpatialTap,
1704
- onSpatialDragStart: _onSpatialDragStart,
1705
- onSpatialDrag: _onSpatialDrag,
1706
- onSpatialDragEnd: _onSpatialDragEnd,
1707
- onSpatialRotate: _onSpatialRotate,
1708
- onSpatialRotateEnd: _onSpatialRotateEnd,
1709
- onSpatialMagnify: _onSpatialMagnify,
1710
- onSpatialMagnifyEnd: _onSpatialMagnifyEnd,
1711
- spatialEventOptions: _spatialEventOptions,
1712
- spatializedContent: _content,
1713
- createSpatializedElement: _create,
1714
- getExtraSpatializedElementProperties: _getExtra,
1715
- extraRefProps: _extraRef,
1716
- sizingMode: _sizingMode,
1717
- onSpatialContentReady: _onSpatialContentReady,
1718
- ...restProps
1719
- } = inprops;
1720
- const [hostEl, setHostEl] = useState6(null);
1721
- const callbackRef = useRef5(_onSpatialContentReady);
1722
- callbackRef.current = _onSpatialContentReady;
1723
- useLayoutEffect2(() => {
1724
- if (!enableOnSpatialContentReadyFallback || !hostEl || !hostEl.isConnected || !callbackRef.current) {
1725
- return () => {
1726
- };
1727
- }
1728
- let cleanup;
1729
- try {
1730
- cleanup = callbackRef.current({ host: hostEl });
1731
- } catch (e) {
1732
- if (process.env.NODE_ENV !== "production") {
1733
- console.error("[WebSpatial] onSpatialContentReady threw", e);
1734
- }
1735
- }
1736
- return () => {
1737
- if (typeof cleanup !== "function") return;
1738
- try {
1739
- cleanup();
1740
- } catch (e) {
1741
- if (process.env.NODE_ENV !== "production") {
1742
- console.error("[WebSpatial] onSpatialContentReady cleanup threw", e);
1743
- }
1744
- }
1745
- };
1746
- }, [enableOnSpatialContentReadyFallback, hostEl]);
1747
- const setHostRef = useCallback6(
1748
- (node) => {
1749
- if (typeof innerRef === "function") {
1750
- innerRef(node);
1751
- } else if (innerRef != null) {
1752
- innerRef.current = node;
1753
- }
1754
- setHostEl(node);
1755
- },
1756
- [innerRef]
1757
- );
1758
- return /* @__PURE__ */ jsx6(Component, { ref: setHostRef, ...restProps, children });
1759
- }
1760
- function SpatializedContainerBase(inprops, ref) {
1761
- const isWebSpatialEnv = getSession() !== null;
1762
- const insideAttachment = useInsideAttachment();
1763
- if (!isWebSpatialEnv || insideAttachment) {
1764
- if (insideAttachment) {
1765
- console.warn(
1766
- `[WebSpatial] ${inprops.component || "Spatial element"} cannot be used inside AttachmentAsset. Rendering as plain HTML.`
1767
- );
1768
- }
1769
- return /* @__PURE__ */ jsx6(
1770
- DegradedContainer,
1771
- {
1772
- ...inprops,
1773
- innerRef: ref,
1774
- enableOnSpatialContentReadyFallback: !isWebSpatialEnv && !insideAttachment
1775
- }
1776
- );
1777
- }
1778
- const layer = useContext7(SpatialLayerContext) + 1;
1779
- const rootSpatializedContainerObject = useContext7(
1780
- SpatializedContainerContext
1781
- );
1782
- const inSpatializedContainer = !!rootSpatializedContainerObject;
1783
- const portalInstanceObject = useContext7(PortalInstanceContext);
1784
- const inPortalInstanceEnv = !!portalInstanceObject;
1785
- const isInStandardInstance = !inPortalInstanceEnv;
1786
- const spatialId = useMemo2(() => {
1787
- return !inSpatializedContainer ? `root_container` : rootSpatializedContainerObject.getSpatialId(layer, isInStandardInstance);
1788
- }, []);
1789
- const spatialIdProps = {
1790
- [SpatialID]: spatialId
1791
- };
1792
- const {
1793
- onSpatialTap,
1794
- onSpatialDragStart,
1795
- onSpatialDrag,
1796
- onSpatialDragEnd,
1797
- onSpatialRotate,
1798
- onSpatialRotateEnd,
1799
- onSpatialMagnify,
1800
- onSpatialMagnifyEnd,
1801
- extraRefProps,
1802
- ...props
1803
- } = inprops;
1804
- if (inSpatializedContainer) {
1805
- if (inPortalInstanceEnv) {
1806
- const spatialEvents = useSpatialEventsWhenSpatializedContainerExist(
1807
- {
1808
- onSpatialTap,
1809
- onSpatialDragStart,
1810
- onSpatialDrag,
1811
- onSpatialDragEnd,
1812
- onSpatialRotate,
1813
- onSpatialRotateEnd,
1814
- onSpatialMagnify,
1815
- onSpatialMagnifyEnd
1816
- },
1817
- spatialId,
1818
- rootSpatializedContainerObject
1819
- );
1820
- return /* @__PURE__ */ jsx6(SpatialLayerContext.Provider, { value: layer, children: /* @__PURE__ */ jsx6(
1821
- PortalSpatializedContainer,
1822
- {
1823
- ...spatialIdProps,
1824
- ...props,
1825
- ...spatialEvents
1826
- }
1827
- ) });
1828
- } else {
1829
- const {
1830
- transformVisibilityTaskContainerCallback,
1831
- standardSpatializedContainerCallback,
1832
- spatialContainerRefProxy
1833
- } = useDomProxy(ref, extraRefProps);
1834
- const [probeClassName, setProbeClassName] = useState6(
1835
- () => props.className ?? ""
1836
- );
1837
- const notifyProbeClass = useCallback6((name) => {
1838
- setProbeClassName((prev) => prev === name ? prev : name);
1839
- }, []);
1840
- useEffect10(() => {
1841
- spatialContainerRefProxy.current.setMirrorClassNotify?.(
1842
- notifyProbeClass
1843
- );
1844
- return () => {
1845
- spatialContainerRefProxy.current.setMirrorClassNotify?.(null);
1846
- };
1847
- }, [spatialContainerRefProxy, notifyProbeClass]);
1848
- useEffect10(() => {
1849
- rootSpatializedContainerObject.updateSpatialContainerRefProxyInfo(
1850
- spatialId,
1851
- spatialContainerRefProxy.current
1852
- );
1853
- }, [spatialContainerRefProxy.current]);
1854
- const {
1855
- spatializedContent,
1856
- createSpatializedElement: createSpatializedElement2,
1857
- getExtraSpatializedElementProperties: getExtraSpatializedElementProperties2,
1858
- spatialEventOptions: _nestedSpatialEventOptions,
1859
- onSpatialContentReady: _nestedOnSpatialContentReady,
1860
- ...restProps
1861
- } = props;
1862
- return /* @__PURE__ */ jsxs2(SpatialLayerContext.Provider, { value: layer, children: [
1863
- /* @__PURE__ */ jsx6(
1864
- StandardSpatializedContainer,
1865
- {
1866
- ref: standardSpatializedContainerCallback,
1867
- ...spatialIdProps,
1868
- ...restProps,
1869
- inStandardSpatializedContainer: true
1870
- }
1871
- ),
1872
- /* @__PURE__ */ jsx6(
1873
- TransformVisibilityTaskContainer,
1874
- {
1875
- ref: transformVisibilityTaskContainerCallback,
1876
- ...spatialIdProps,
1877
- className: probeClassName,
1878
- style: props.style
1879
- }
1880
- )
1881
- ] });
1882
- }
1883
- } else {
1884
- const {
1885
- transformVisibilityTaskContainerCallback,
1886
- standardSpatializedContainerCallback,
1887
- spatialContainerRefProxy
1888
- } = useDomProxy(ref, extraRefProps);
1889
- const [probeClassName, setProbeClassName] = useState6(
1890
- () => props.className ?? ""
1891
- );
1892
- const notifyProbeClass = useCallback6((name) => {
1893
- setProbeClassName((prev) => prev === name ? prev : name);
1894
- }, []);
1895
- useEffect10(() => {
1896
- spatialContainerRefProxy.current.setMirrorClassNotify?.(notifyProbeClass);
1897
- return () => {
1898
- spatialContainerRefProxy.current.setMirrorClassNotify?.(null);
1899
- };
1900
- }, [spatialContainerRefProxy, notifyProbeClass]);
1901
- const spatialEvents = useSpatialEvents(
1902
- {
1903
- onSpatialTap,
1904
- onSpatialDragStart,
1905
- onSpatialDrag,
1906
- onSpatialDragEnd,
1907
- onSpatialRotate,
1908
- onSpatialRotateEnd,
1909
- onSpatialMagnify,
1910
- onSpatialMagnifyEnd
1911
- },
1912
- spatialContainerRefProxy
1913
- );
1914
- const spatializedContainerObject = useMemo2(
1915
- () => new SpatializedContainerObject(),
1916
- []
1917
- );
1918
- const {
1919
- spatializedContent,
1920
- createSpatializedElement: createSpatializedElement2,
1921
- getExtraSpatializedElementProperties: getExtraSpatializedElementProperties2,
1922
- spatialEventOptions: _rootSpatialEventOptions,
1923
- onSpatialContentReady: _rootOnSpatialContentReady,
1924
- ...restProps
1925
- } = props;
1926
- return /* @__PURE__ */ jsx6(SpatialLayerContext.Provider, { value: layer, children: /* @__PURE__ */ jsxs2(
1927
- SpatializedContainerContext.Provider,
1928
- {
1929
- value: spatializedContainerObject,
1930
- children: [
1931
- /* @__PURE__ */ jsx6(
1932
- StandardSpatializedContainer,
1933
- {
1934
- ref: standardSpatializedContainerCallback,
1935
- ...spatialIdProps,
1936
- ...restProps,
1937
- inStandardSpatializedContainer: false
1938
- }
1939
- ),
1940
- /* @__PURE__ */ jsx6(
1941
- PortalSpatializedContainer,
1942
- {
1943
- ...spatialIdProps,
1944
- ...props,
1945
- ...spatialEvents
1946
- }
1947
- ),
1948
- /* @__PURE__ */ jsx6(
1949
- TransformVisibilityTaskContainer,
1950
- {
1951
- ref: transformVisibilityTaskContainerCallback,
1952
- ...spatialIdProps,
1953
- className: probeClassName,
1954
- style: props.style
1955
- }
1956
- )
1957
- ]
1958
- }
1959
- ) });
1960
- }
1961
- }
1962
- var SpatializedContainer = withSSRSupported(
1963
- forwardRef4(SpatializedContainerBase)
1964
- );
1965
-
1966
- // src/spatialized-container/Spatialized2DElementContainer.tsx
1967
- import { createPortal as createPortal2 } from "react-dom";
1968
- import {
1969
- forwardRef as forwardRef5,
1970
- useCallback as useCallback7,
1971
- useContext as useContext8,
1972
- useEffect as useEffect12,
1973
- useState as useState7
1974
- } from "react";
1975
-
1976
- // src/utils/windowStyleSync.ts
1977
- function asyncLoadStyleToChildWindow(childWindow, link, isCurrent) {
1978
- return new Promise((resolve) => {
1979
- const { href } = link;
1980
- const sep = href.includes("?") ? "&" : "?";
1981
- link.href = `${href}${sep}uniqueURL=${Math.random()}`;
1982
- let finished = false;
1983
- const finish = (ok) => {
1984
- if (finished) return;
1985
- finished = true;
1986
- resolve(ok);
1987
- };
1988
- link.onerror = () => {
1989
- finish(false);
1990
- };
1991
- link.onload = () => {
1992
- if (!isCurrent()) {
1993
- link.parentNode?.removeChild(link);
1994
- finish(false);
1995
- return;
1996
- }
1997
- finish(true);
1998
- };
1999
- setTimeout(() => {
2000
- if (!isCurrent()) {
2001
- finish(false);
2002
- return;
2003
- }
2004
- childWindow.document.head.appendChild(link);
2005
- }, 50);
2006
- });
2007
- }
2008
- var WEBSPATIAL_SYNC_ATTR = "data-webspatial-sync";
2009
- var WEBSPATIAL_SYNC_KEY_ATTR = "data-webspatial-sync-key";
2010
- function setOpenWindowStyle(openedWindow) {
2011
- openedWindow.document.documentElement.style.cssText += document.documentElement.style.cssText;
2012
- openedWindow.document.documentElement.style.backgroundColor = "transparent";
2013
- openedWindow.document.body.style.margin = "0px";
2014
- openedWindow.document.body.style.display = "inline-block";
2015
- openedWindow.document.body.style.minWidth = "auto";
2016
- openedWindow.document.body.style.minHeight = "auto";
2017
- openedWindow.document.body.style.maxWidth = "fit-content";
2018
- openedWindow.document.body.style.minWidth = "fit-content";
2019
- openedWindow.document.body.style.background = "transparent";
2020
- }
2021
- var controllers = /* @__PURE__ */ new WeakMap();
2022
- function getController(childWindow) {
2023
- const prev = controllers.get(childWindow);
2024
- if (prev) return prev;
2025
- const next = { version: 0 };
2026
- controllers.set(childWindow, next);
2027
- return next;
2028
- }
2029
- async function syncParentHeadToChild(childWindow) {
2030
- const controller = getController(childWindow);
2031
- const version2 = ++controller.version;
2032
- const styleLoadedPromises = [];
2033
- const { head } = childWindow.document;
2034
- const isCurrent = () => controller.version === version2;
2035
- const parentStyles = Array.from(document.head.querySelectorAll("style"));
2036
- const parentStylesheets = Array.from(
2037
- document.head.querySelectorAll('link[rel="stylesheet"][href]')
2038
- );
2039
- const desiredStylesheetKeys = /* @__PURE__ */ new Set();
2040
- for (const link of parentStylesheets) {
2041
- if (link.href) desiredStylesheetKeys.add(link.href);
2042
- }
2043
- const existingSyncedLinks = Array.from(
2044
- head.querySelectorAll(
2045
- `link[rel="stylesheet"][${WEBSPATIAL_SYNC_ATTR}="1"]`
2046
- )
2047
- );
2048
- for (const link of existingSyncedLinks) {
2049
- const key = link.getAttribute(WEBSPATIAL_SYNC_KEY_ATTR) ?? link.href;
2050
- if (!desiredStylesheetKeys.has(key)) link.parentNode?.removeChild(link);
2051
- }
2052
- const prevSyncedStyles = head.querySelectorAll(
2053
- `style[${WEBSPATIAL_SYNC_ATTR}="1"]`
2054
- );
2055
- prevSyncedStyles.forEach((n) => n.parentNode?.removeChild(n));
2056
- for (const styleEl of parentStyles) {
2057
- const node = styleEl.cloneNode(true);
2058
- node.setAttribute(WEBSPATIAL_SYNC_ATTR, "1");
2059
- head.appendChild(node);
2060
- }
2061
- const currentKeys = /* @__PURE__ */ new Set();
2062
- const currentSyncedLinks = Array.from(
2063
- head.querySelectorAll(
2064
- `link[rel="stylesheet"][${WEBSPATIAL_SYNC_ATTR}="1"]`
2065
- )
2066
- );
2067
- for (const link of currentSyncedLinks) {
2068
- currentKeys.add(link.getAttribute(WEBSPATIAL_SYNC_KEY_ATTR) ?? link.href);
2069
- }
2070
- for (const link of parentStylesheets) {
2071
- const key = link.href;
2072
- if (!key || currentKeys.has(key)) continue;
2073
- const node = link.cloneNode(true);
2074
- node.setAttribute(WEBSPATIAL_SYNC_ATTR, "1");
2075
- node.setAttribute(WEBSPATIAL_SYNC_KEY_ATTR, key);
2076
- styleLoadedPromises.push(
2077
- asyncLoadStyleToChildWindow(childWindow, node, isCurrent)
2078
- );
2079
- }
2080
- childWindow.document.documentElement.className = document.documentElement.className;
2081
- return Promise.all(styleLoadedPromises);
2082
- }
2083
-
2084
- // src/utils/useSyncHeadStyles.ts
2085
- import { useEffect as useEffect11 } from "react";
2086
- function getSyncTiming(mutations) {
2087
- if (!Array.isArray(mutations) || mutations.length === 0) return null;
2088
- let hasDelayed = false;
2089
- for (const mutation of mutations) {
2090
- if (mutation.type === "characterData") {
2091
- const parent = mutation.target.parentElement;
2092
- if (parent?.tagName === "STYLE") return "immediate";
2093
- }
2094
- const nodes = [
2095
- mutation.target,
2096
- ...Array.from(mutation.addedNodes),
2097
- ...Array.from(mutation.removedNodes)
2098
- ];
2099
- for (const node of nodes) {
2100
- if (!(node instanceof Element)) continue;
2101
- const tag = node.tagName;
2102
- if (tag === "STYLE") return "immediate";
2103
- if (tag === "LINK") {
2104
- const { rel } = node;
2105
- if (rel && rel.toLowerCase() === "stylesheet") hasDelayed = true;
2106
- }
2107
- }
2108
- }
2109
- return hasDelayed ? "delayed" : null;
2110
- }
2111
- function useSyncHeadStyles(childWindow, options) {
2112
- const delayMs = 100;
2113
- const subtree = options?.subtree ?? true;
2114
- const immediate = options?.immediate ?? true;
2115
- useEffect11(() => {
2116
- if (!childWindow) return;
2117
- let timer;
2118
- let immediateQueued = false;
2119
- let disposed = false;
2120
- const scheduleSync = (timing = "delayed") => {
2121
- if (timer) window.clearTimeout(timer);
2122
- if (timing === "immediate") {
2123
- if (immediateQueued) return;
2124
- immediateQueued = true;
2125
- queueMicrotask(() => {
2126
- immediateQueued = false;
2127
- if (disposed) return;
2128
- syncParentHeadToChild(childWindow);
2129
- });
2130
- return;
2131
- }
2132
- timer = window.setTimeout(() => {
2133
- if (disposed) return;
2134
- syncParentHeadToChild(childWindow);
2135
- }, delayMs);
2136
- };
2137
- if (immediate) scheduleSync();
2138
- const observer = new MutationObserver((mutations) => {
2139
- const timing = getSyncTiming(mutations);
2140
- if (!timing) return;
2141
- scheduleSync(timing);
2142
- });
2143
- observer.observe(document.head, {
2144
- childList: true,
2145
- characterData: true,
2146
- subtree
2147
- });
2148
- return () => {
2149
- disposed = true;
2150
- if (timer) window.clearTimeout(timer);
2151
- observer.disconnect();
2152
- };
2153
- }, [childWindow, delayMs, subtree, immediate]);
2154
- }
2155
-
2156
- // src/spatialized-container/hooks/useSpatialContentReady.ts
2157
- import { useLayoutEffect as useLayoutEffect3, useRef as useRef6 } from "react";
2158
- var isDev = process.env.NODE_ENV !== "production";
2159
- function safeInvokeCleanup(cleanup) {
2160
- if (!cleanup) return;
2161
- try {
2162
- cleanup();
2163
- } catch (e) {
2164
- if (isDev) {
2165
- console.error("[WebSpatial] onSpatialContentReady cleanup threw", e);
2166
- }
2167
- }
2168
- }
2169
- function useSpatialContentReady(params) {
2170
- const {
2171
- spatializedElement,
2172
- portalInstanceObject,
2173
- hostElement,
2174
- onSpatialContentReady
2175
- } = params;
2176
- const callbackRef = useRef6(onSpatialContentReady);
2177
- callbackRef.current = onSpatialContentReady;
2178
- useLayoutEffect3(() => {
2179
- const dom = portalInstanceObject.dom;
2180
- const isReady = !!(spatializedElement && dom && hostElement && hostElement.isConnected);
2181
- if (!isReady || !hostElement) {
2182
- return () => {
2183
- };
2184
- }
2185
- const cb = callbackRef.current;
2186
- let cleanupFromCallback;
2187
- if (cb) {
2188
- try {
2189
- const ret = cb({ host: hostElement });
2190
- cleanupFromCallback = typeof ret === "function" ? ret : void 0;
2191
- } catch (e) {
2192
- if (isDev) {
2193
- console.error("[WebSpatial] onSpatialContentReady threw", e);
2194
- }
2195
- }
2196
- }
2197
- return () => {
2198
- safeInvokeCleanup(cleanupFromCallback);
2199
- };
2200
- }, [spatializedElement, portalInstanceObject.dom, hostElement]);
2201
- }
2202
-
2203
- // src/spatialized-container/Spatialized2DElementContainer.tsx
2204
- import { jsx as jsx7 } from "react/jsx-runtime";
2205
- function mergeRefs(...refs) {
2206
- return (value) => {
2207
- for (const ref of refs) {
2208
- if (ref == null) continue;
2209
- if (typeof ref === "function") {
2210
- ref(value);
2211
- } else {
2212
- ;
2213
- ref.current = value;
2214
- }
2215
- }
2216
- };
2217
- }
2218
- function getJSXPortalInstance(inProps, portalInstanceObject, hostRef) {
2219
- const {
2220
- component: El,
2221
- style: inStyle = {},
2222
- ref: userRef,
2223
- ...props
2224
- } = inProps;
2225
- const extraStyle = {
2226
- visibility: "visible",
2227
- position: "relative",
2228
- top: "0px",
2229
- left: "0px",
2230
- margin: "0px",
2231
- marginLeft: "0px",
2232
- marginRight: "0px",
2233
- marginTop: "0px",
2234
- marginBottom: "0px",
2235
- borderRadius: "0px",
2236
- // overflow: '',
2237
- transform: "none"
2238
- };
2239
- const computedStyle = portalInstanceObject.computedStyle;
2240
- const inheritedPortalStyle = getInheritedStyleProps(computedStyle);
2241
- const style = {
2242
- ...inStyle,
2243
- ...inheritedPortalStyle,
2244
- ...extraStyle
2245
- };
2246
- const mergedRef = hostRef != null ? mergeRefs(hostRef, userRef) : userRef;
2247
- return /* @__PURE__ */ jsx7(El, { ref: mergedRef, style, ...props });
2248
- }
2249
- function useSyncDocumentTitle(windowProxy, spatializedElement, name) {
2250
- useEffect12(() => {
2251
- windowProxy.document.title = name;
2252
- spatializedElement.updateProperties({
2253
- name
2254
- });
2255
- }, [name]);
2256
- }
2257
- function SpatializedContent(props) {
2258
- const { spatializedElement, onSpatialContentReady, ...restProps } = props;
2259
- const spatialized2DElement = spatializedElement;
2260
- const { windowProxy } = spatialized2DElement;
2261
- const [hostEl, setHostEl] = useState7(null);
2262
- const portalInstanceObject = useContext8(
2263
- PortalInstanceContext
2264
- );
2265
- useSpatialContentReady({
2266
- spatializedElement,
2267
- portalInstanceObject,
2268
- hostElement: hostEl,
2269
- onSpatialContentReady
2270
- });
2271
- useSyncHeadStyles(windowProxy, {
2272
- subtree: false
2273
- });
2274
- const name = restProps["data-name"] || "";
2275
- useSyncDocumentTitle(windowProxy, spatialized2DElement, name);
2276
- const setHostCallback = useCallback7((el) => {
2277
- setHostEl(el);
2278
- }, []);
2279
- const JSXPortalInstance = getJSXPortalInstance(
2280
- restProps,
2281
- portalInstanceObject,
2282
- setHostCallback
2283
- );
2284
- return createPortal2(JSXPortalInstance, windowProxy.document.body);
2285
- }
2286
- function getExtraSpatializedElementProperties(computedStyle) {
2287
- const overflow = computedStyle.getPropertyValue("overflow");
2288
- const scrollPageEnabled = ["visible", "hidden", "clip"].indexOf(overflow) >= 0;
2289
- const material = computedStyle.getPropertyValue(
2290
- SpatialCustomStyleVars.backgroundMaterial
2291
- );
2292
- const properties = {};
2293
- properties.scrollPageEnabled = scrollPageEnabled;
2294
- properties.cornerRadius = parseCornerRadius(computedStyle);
2295
- if (material) {
2296
- properties.material = material;
2297
- }
2298
- return properties;
2299
- }
2300
- async function createSpatializedElement() {
2301
- const spatializedElement = await getSession().createSpatialized2DElement();
2302
- const { windowProxy } = spatializedElement;
2303
- setOpenWindowStyle(windowProxy);
2304
- await syncParentHeadToChild(windowProxy);
2305
- const viewport = windowProxy.document.querySelector('meta[name="viewport"]');
2306
- if (viewport) {
2307
- viewport?.setAttribute(
2308
- "content",
2309
- " initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
2310
- );
2311
- } else {
2312
- const meta = windowProxy.document.createElement("meta");
2313
- meta.name = "viewport";
2314
- meta.content = "initial-scale=1.0, maximum-scale=1.0, user-scalable=no";
2315
- windowProxy.document.head.appendChild(meta);
2316
- }
2317
- return spatializedElement;
2318
- }
2319
- function Spatialized2DElementContainerBase(props, ref) {
2320
- return /* @__PURE__ */ jsx7(
2321
- SpatializedContainer,
2322
- {
2323
- ref,
2324
- createSpatializedElement,
2325
- getExtraSpatializedElementProperties,
2326
- spatializedContent: SpatializedContent,
2327
- ...props
2328
- }
2329
- );
2330
- }
2331
- var Spatialized2DElementContainer = forwardRef5(
2332
- Spatialized2DElementContainerBase
2333
- );
2334
-
2335
- // src/spatialized-container/SpatializedStatic3DElementContainer.tsx
2336
- import {
2337
- Children,
2338
- forwardRef as forwardRef6,
2339
- isValidElement,
2340
- useCallback as useCallback8,
2341
- useContext as useContext9,
2342
- useEffect as useEffect13,
2343
- useMemo as useMemo3,
2344
- useRef as useRef7
2345
- } from "react";
2346
- import { Fragment as Fragment2, jsx as jsx8 } from "react/jsx-runtime";
2347
- function getAbsoluteURL(url) {
2348
- if (!url) return url;
2349
- try {
2350
- return new URL(url, document.baseURI).toString();
2351
- } catch {
2352
- return url;
2353
- }
2354
- }
2355
- function createLoadEvent(type, targetGetter) {
2356
- const event = new CustomEvent(type, {
2357
- bubbles: false,
2358
- cancelable: false
2359
- });
2360
- const proxyEvent = new Proxy(event, {
2361
- get(target, prop) {
2362
- if (prop === "target") {
2363
- return targetGetter();
2364
- }
2365
- return Reflect.get(target, prop);
2366
- }
2367
- });
2368
- return proxyEvent;
2369
- }
2370
- function createLoadFailureEvent(targetGetter) {
2371
- return createLoadEvent("modelloadfailed", targetGetter);
2372
- }
2373
- function createLoadSuccessEvent(targetGetter) {
2374
- return createLoadEvent("modelloaded", targetGetter);
2375
- }
2376
- function collectSources(children) {
2377
- const sources = [];
2378
- Children.forEach(children, (child) => {
2379
- if (isValidElement(child) && child.type === "source") {
2380
- const { src, type } = child.props;
2381
- if (src) {
2382
- sources.push({ src: getAbsoluteURL(src), type });
2383
- }
2384
- }
2385
- });
2386
- return sources;
2387
- }
2388
- function SpatializedContent2(props) {
2389
- const {
2390
- src,
2391
- poster,
2392
- children,
2393
- spatializedElement,
2394
- onLoad,
2395
- onError,
2396
- autoPlay,
2397
- loop,
2398
- loading = "eager"
2399
- } = props;
2400
- const portalInstanceObject = useContext9(PortalInstanceContext);
2401
- const wasVisible = useRef7(false);
2402
- const modelURL = useMemo3(() => getAbsoluteURL(src), [src]);
2403
- const posterURL = useMemo3(() => getAbsoluteURL(poster), [poster]);
2404
- const sources = useMemo3(() => collectSources(children), [children]);
2405
- const sourcesKey = useMemo3(() => JSON.stringify(sources), [sources]);
2406
- useEffect13(() => {
2407
- wasVisible.current = false;
2408
- const target = portalInstanceObject.dom;
2409
- if (loading !== "lazy" || !target) {
2410
- wasVisible.current = true;
2411
- return;
2412
- }
2413
- const observer = new IntersectionObserver((entries) => {
2414
- if (entries.some((entry) => entry.isIntersecting)) {
2415
- wasVisible.current = true;
2416
- observer.disconnect();
2417
- spatializedElement.updateProperties({ loading: "eager" });
2418
- }
2419
- });
2420
- observer.observe(target);
2421
- return () => observer.disconnect();
2422
- }, [modelURL, sourcesKey, portalInstanceObject]);
2423
- useEffect13(() => {
2424
- if (loading !== "lazy") wasVisible.current = true;
2425
- spatializedElement.updateProperties({
2426
- modelURL: modelURL ?? (spatializedElement.modelUrl ? "" : modelURL),
2427
- sources,
2428
- autoplay: autoPlay,
2429
- loop,
2430
- posterURL: posterURL ?? "",
2431
- loading: loading === "lazy" && wasVisible.current ? "eager" : loading
2432
- });
2433
- }, [modelURL, sourcesKey, autoPlay, loop, posterURL, loading]);
2434
- useEffect13(() => {
2435
- if (onLoad) {
2436
- spatializedElement.onLoadCallback = () => {
2437
- onLoad(
2438
- createLoadSuccessEvent(
2439
- () => portalInstanceObject.dom
2440
- )
2441
- );
2442
- };
2443
- } else {
2444
- spatializedElement.onLoadCallback = void 0;
2445
- }
2446
- }, [onLoad]);
2447
- useEffect13(() => {
2448
- if (onError) {
2449
- spatializedElement.onLoadFailureCallback = () => {
2450
- onError(
2451
- createLoadFailureEvent(
2452
- () => portalInstanceObject.dom
2453
- )
2454
- );
2455
- };
2456
- } else {
2457
- spatializedElement.onLoadFailureCallback = void 0;
2458
- }
2459
- }, [onError]);
2460
- return /* @__PURE__ */ jsx8(Fragment2, {});
2461
- }
2462
- function SpatializedStatic3DElementContainerBase(props, ref) {
2463
- const promiseRef = useRef7(null);
2464
- const createSpatializedElement2 = useCallback8(() => {
2465
- promiseRef.current = getSession().createSpatializedStatic3DElement(
2466
- getAbsoluteURL(props.src),
2467
- collectSources(props.children),
2468
- props.loading === "lazy" ? "lazy" : "eager"
2469
- );
2470
- return promiseRef.current;
2471
- }, []);
2472
- const extraRefProps = useCallback8(
2473
- (domProxy) => {
2474
- let modelTransform = new DOMMatrixReadOnly();
2475
- return {
2476
- get currentSrc() {
2477
- const spatializedElement = domProxy.__spatializedElement;
2478
- return spatializedElement?.currentSrc ?? "";
2479
- },
2480
- get ready() {
2481
- return promiseRef.current.then((spatializedElement) => spatializedElement.ready).then((success) => {
2482
- if (success) return createLoadSuccessEvent(() => domProxy);
2483
- throw createLoadFailureEvent(() => domProxy);
2484
- });
2485
- },
2486
- get entityTransform() {
2487
- return modelTransform;
2488
- },
2489
- set entityTransform(value) {
2490
- modelTransform = value;
2491
- const spatializedElement = domProxy.__spatializedElement;
2492
- spatializedElement?.updateModelTransform(modelTransform);
2493
- },
2494
- async play() {
2495
- const spatializedElement = domProxy.__spatializedElement;
2496
- await spatializedElement?.play();
2497
- },
2498
- async pause() {
2499
- const spatializedElement = domProxy.__spatializedElement;
2500
- await spatializedElement?.pause();
2501
- },
2502
- get paused() {
2503
- const spatializedElement = domProxy.__spatializedElement;
2504
- return spatializedElement?.paused ?? true;
2505
- },
2506
- get duration() {
2507
- const spatializedElement = domProxy.__spatializedElement;
2508
- return spatializedElement?.duration ?? 0;
2509
- },
2510
- get playbackRate() {
2511
- const spatializedElement = domProxy.__spatializedElement;
2512
- return spatializedElement?.playbackRate ?? 1;
2513
- },
2514
- set playbackRate(value) {
2515
- const spatializedElement = domProxy.__spatializedElement;
2516
- if (spatializedElement) {
2517
- spatializedElement.playbackRate = value;
2518
- }
2519
- },
2520
- get currentTime() {
2521
- const spatializedElement = domProxy.__spatializedElement;
2522
- return spatializedElement?.currentTime ?? 0;
2523
- },
2524
- set currentTime(value) {
2525
- const spatializedElement = domProxy.__spatializedElement;
2526
- if (spatializedElement) {
2527
- spatializedElement.currentTime = value;
2528
- }
2529
- }
2530
- };
2531
- },
2532
- []
2533
- );
2534
- return /* @__PURE__ */ jsx8(
2535
- SpatializedContainer,
2536
- {
2537
- ref,
2538
- component: "div",
2539
- createSpatializedElement: createSpatializedElement2,
2540
- spatializedContent: SpatializedContent2,
2541
- extraRefProps,
2542
- ...props
2543
- }
2544
- );
2545
- }
2546
- var SpatializedStatic3DElementContainer = forwardRef6(
2547
- SpatializedStatic3DElementContainerBase
2548
- );
2549
-
2550
- // src/spatialized-container/Spatialized2DElementContainerFactory.tsx
2551
- import { forwardRef as forwardRef7 } from "react";
2552
- import { jsx as jsx9 } from "react/jsx-runtime";
2553
- var CachedSpatialized2DElementContainerType = /* @__PURE__ */ new Map();
2554
- function withSpatialized2DElementContainer(Component) {
2555
- if (CachedSpatialized2DElementContainerType.has(Component)) {
2556
- return CachedSpatialized2DElementContainerType.get(Component);
2557
- } else {
2558
- const TypedSpatialized2DElementContainer = forwardRef7(
2559
- (givenProps, ref) => {
2560
- const { component: ignoreComponent, ...props } = givenProps;
2561
- return /* @__PURE__ */ jsx9(
2562
- Spatialized2DElementContainer,
2563
- {
2564
- component: Component,
2565
- ...props,
2566
- ref
2567
- }
2568
- );
2569
- }
2570
- );
2571
- CachedSpatialized2DElementContainerType.set(
2572
- Component,
2573
- TypedSpatialized2DElementContainer
2574
- );
2575
- CachedSpatialized2DElementContainerType.set(
2576
- TypedSpatialized2DElementContainer,
2577
- TypedSpatialized2DElementContainer
2578
- );
2579
- return TypedSpatialized2DElementContainer;
2580
- }
2581
- }
2582
-
2583
- // src/spatialized-container/index.ts
2584
- function initPolyfill() {
2585
- injectSpatialDefaultStyle();
2586
- initCSSParserDivContainer();
2587
- }
2588
-
2589
- // src/webSpatialRuntime.ts
2590
- var WebSpatialRuntime = {
2591
- supports
2592
- };
2593
-
2594
- // src/initScene.web.ts
2595
- function initScene(name, callback) {
2596
- return;
2597
- }
2598
-
2599
- // src/spatialized-container-monitor/withSpatialMonitor.tsx
2600
- import { forwardRef as forwardRef9 } from "react";
2601
-
2602
- // src/spatialized-container-monitor/useMonitorDomChange.tsx
2603
- import { useRef as useRef8, useEffect as useEffect14, useMemo as useMemo4 } from "react";
2604
- function useMonitorDomChange(inRef) {
2605
- const ref = useRef8(null);
2606
- useEffect14(() => {
2607
- const observer = new MutationObserver((mutationsList) => {
2608
- notifyDOMUpdate(mutationsList);
2609
- });
2610
- const config = {
2611
- childList: true,
2612
- subtree: true,
2613
- attributes: true,
2614
- attributeFilter: ["style", "class"]
2615
- };
2616
- ref.current && observer.observe(ref.current, config);
2617
- return () => {
2618
- observer.disconnect();
2619
- };
2620
- }, []);
2621
- const proxyRef = useMemo4(
2622
- () => new Proxy(ref, {
2623
- set: function(target, key, value) {
2624
- if (key === "current") {
2625
- if (inRef) {
2626
- if (typeof inRef === "function") {
2627
- inRef(value);
2628
- } else if (inRef) {
2629
- inRef.current = value;
2630
- }
2631
- }
2632
- }
2633
- return Reflect.set(target, key, value);
2634
- }
2635
- }),
2636
- []
2637
- );
2638
- return proxyRef;
2639
- }
2640
-
2641
- // src/spatialized-container-monitor/useMonitorDocumentHeaderChange.tsx
2642
- import { useEffect as useEffect15 } from "react";
2643
- function useMonitorDocumentHeaderChange() {
2644
- useEffect15(() => {
2645
- const observer = new MutationObserver((mutationsList) => {
2646
- notifyUpdateStandInstanceLayout();
2647
- });
2648
- const config = {
2649
- childList: true,
2650
- subtree: true,
2651
- attributes: true
2652
- };
2653
- observer.observe(document.head, config);
2654
- return () => {
2655
- observer.disconnect();
2656
- };
2657
- }, []);
2658
- }
2659
-
2660
- // src/spatialized-container-monitor/SpatialMonitor.tsx
2661
- import { forwardRef as forwardRef8 } from "react";
2662
- import { jsx as jsx10 } from "react/jsx-runtime";
2663
- function SpatialMonitorBase(inProps, inRef) {
2664
- const { El = "div", ...props } = inProps;
2665
- const ref = useMonitorDomChange(inRef);
2666
- useMonitorDocumentHeaderChange();
2667
- return /* @__PURE__ */ jsx10(El, { ...props, ref });
2668
- }
2669
- var SpatialMonitor = forwardRef8(SpatialMonitorBase);
2670
-
2671
- // src/spatialized-container-monitor/withSpatialMonitor.tsx
2672
- import { jsx as jsx11 } from "react/jsx-runtime";
2673
- var cachedWithSpatialMonitorType = /* @__PURE__ */ new Map();
2674
- function withSpatialMonitor(El) {
2675
- if (cachedWithSpatialMonitorType.has(El)) {
2676
- return cachedWithSpatialMonitorType.get(El);
2677
- } else {
2678
- const WithSpatialMonitorComponent = forwardRef9(
2679
- (givenProps, givenRef) => {
2680
- const {
2681
- El: _,
2682
- ...props
2683
- } = givenProps;
2684
- return /* @__PURE__ */ jsx11(SpatialMonitor, { El, ...props, ref: givenRef });
2685
- }
2686
- );
2687
- WithSpatialMonitorComponent.displayName = `WithSpatialMonitor(${typeof El === "string" ? El : El.displayName || El.name})`;
2688
- cachedWithSpatialMonitorType.set(El, WithSpatialMonitorComponent);
2689
- cachedWithSpatialMonitorType.set(
2690
- cachedWithSpatialMonitorType,
2691
- cachedWithSpatialMonitorType
2692
- );
2693
- return WithSpatialMonitorComponent;
2694
- }
2695
- }
2696
-
2697
- // src/reality/components/Entity.tsx
2698
- import { forwardRef as forwardRef11 } from "react";
2699
-
2700
- // src/reality/components/BaseEntity.tsx
2701
- import { forwardRef as forwardRef10 } from "react";
2702
-
2703
- // src/reality/context/RealityContext.tsx
2704
- import { createContext as createContext6, useContext as useContext10 } from "react";
2705
- var RealityContext = createContext6(null);
2706
- var useRealityContext = () => useContext10(RealityContext);
2707
-
2708
- // src/reality/context/ParentContext.tsx
2709
- import { createContext as createContext7, useContext as useContext11 } from "react";
2710
- var ParentContext = createContext7(null);
2711
- var useParentContext = () => useContext11(ParentContext);
2712
-
2713
- // src/reality/context/AttachmentContext.tsx
2714
- import { createContext as createContext8, useContext as useContext12 } from "react";
2715
- var AttachmentRegistry = class {
2716
- // name → (instanceId → container)
2717
- containers = /* @__PURE__ */ new Map();
2718
- listeners = /* @__PURE__ */ new Map();
2719
- addContainer(name, instanceId, container) {
2720
- if (!this.containers.has(name)) {
2721
- this.containers.set(name, /* @__PURE__ */ new Map());
2722
- }
2723
- this.containers.get(name).set(instanceId, container);
2724
- this.notifyListeners(name);
2725
- }
2726
- removeContainer(name, instanceId) {
2727
- this.containers.get(name)?.delete(instanceId);
2728
- if (this.containers.get(name)?.size === 0) {
2729
- this.containers.delete(name);
2730
- }
2731
- this.notifyListeners(name);
2732
- }
2733
- getContainers(name) {
2734
- const map = this.containers.get(name);
2735
- if (!map) return [];
2736
- return Array.from(map, ([instanceId, container]) => ({
2737
- instanceId,
2738
- container
2739
- }));
2740
- }
2741
- onContainersChange(name, cb) {
2742
- const current = this.getContainers(name);
2743
- if (current.length > 0) {
2744
- cb(current);
2745
- }
2746
- const prev = this.listeners.get(name);
2747
- if (prev) prev([]);
2748
- this.listeners.set(name, cb);
2749
- return () => {
2750
- if (this.listeners.get(name) === cb) {
2751
- this.listeners.delete(name);
2752
- }
2753
- };
2754
- }
2755
- notifyListeners(name) {
2756
- const cs = this.getContainers(name);
2757
- this.listeners.get(name)?.(cs);
2758
- }
2759
- destroy() {
2760
- this.containers.clear();
2761
- this.listeners.clear();
2762
- }
2763
- };
2764
- var AttachmentContext = createContext8(null);
2765
-
2766
- // src/reality/hooks/useEntityTransform.tsx
2767
- import { useEffect as useEffect16, useRef as useRef9 } from "react";
2768
-
2769
- // src/reality/utils/ResourceRegistry.ts
2770
- var ResourceRegistry = class {
2771
- /** Every id maps to a promise — either the real resource from add(), or a placeholder until then. */
2772
- resources = /* @__PURE__ */ new Map();
2773
- /** If get() ran first, we stash resolve/reject so add() can complete the waiting promise. */
2774
- deferreds = /* @__PURE__ */ new Map();
2775
- /** Subscribers are notified whenever an id gets a fresh resolved or failed resource attempt. */
2776
- listeners = /* @__PURE__ */ new Map();
2777
- add(id, resource) {
2778
- this.resources.set(id, resource);
2779
- const deferred = this.deferreds.get(id);
2780
- if (deferred) {
2781
- resource.then(deferred.resolve).catch(
2782
- (err) => deferred.reject(err instanceof Error ? err : new Error(String(err)))
2783
- );
2784
- this.deferreds.delete(id);
2785
- }
2786
- resource.then(() => this.notify(id)).catch(() => this.notify(id));
2787
- }
2788
- subscribe(id, listener) {
2789
- const listeners = this.listeners.get(id) ?? /* @__PURE__ */ new Set();
2790
- listeners.add(listener);
2791
- this.listeners.set(id, listeners);
2792
- return () => {
2793
- listeners.delete(listener);
2794
- if (listeners.size === 0) {
2795
- this.listeners.delete(id);
2796
- }
2797
- };
2798
- }
2799
- notify(id) {
2800
- const listeners = this.listeners.get(id);
2801
- if (!listeners) return;
2802
- for (const listener of Array.from(listeners)) {
2803
- listener();
2804
- }
2805
- }
2806
- get(id) {
2807
- const existing = this.resources.get(id);
2808
- if (existing) {
2809
- return existing;
2810
- }
2811
- const promise = new Promise((resolve, reject) => {
2812
- this.deferreds.set(id, { resolve, reject });
2813
- });
2814
- this.resources.set(id, promise);
2815
- return promise;
2816
- }
2817
- remove(id) {
2818
- this.resources.delete(id);
2819
- this.deferreds.delete(id);
2820
- this.notify(id);
2821
- }
2822
- // Same as remove, but when the promise resolves, destroy the spatial object (best-effort).
2823
- removeAndDestroy(id) {
2824
- const p = this.resources.get(id);
2825
- if (p) {
2826
- p.then((obj) => obj.destroy()).catch(() => {
2827
- });
2828
- }
2829
- this.resources.delete(id);
2830
- this.deferreds.delete(id);
2831
- this.notify(id);
2832
- }
2833
- destroy() {
2834
- for (const [id, deferred] of this.deferreds) {
2835
- deferred.reject(
2836
- new Error(`ResourceRegistry destroyed \u2014 "${id}" never resolved`)
2837
- );
2838
- }
2839
- this.deferreds.clear();
2840
- const ids = Array.from(this.resources.keys());
2841
- for (const id of ids) {
2842
- this.notify(id);
2843
- }
2844
- this.listeners.clear();
2845
- const pending = Array.from(this.resources.values());
2846
- this.resources.clear();
2847
- void Promise.allSettled(pending.map((p) => p.then((obj) => obj.destroy())));
2848
- }
2849
- };
2850
-
2851
- // src/reality/utils/equal.ts
2852
- function shallowEqualVec3(a, b) {
2853
- if (a === b) return true;
2854
- if (!a || !b) return false;
2855
- return a.x === b.x && a.y === b.y && a.z === b.z;
2856
- }
2857
- function shallowEqualRotation(a, b) {
2858
- if (a === b) return true;
2859
- if (!a || !b) return false;
2860
- return a.x === b.x && a.y === b.y && a.z === b.z && ("w" in a ? a.w === b.w : true);
2861
- }
2862
- function shallowEqualObject(a, b) {
2863
- if (a === b) return true;
2864
- if (!a || !b) return false;
2865
- const keysA = Object.keys(a);
2866
- const keysB = Object.keys(b);
2867
- if (keysA.length !== keysB.length) return false;
2868
- return keysA.every((key) => a[key] === b[key]);
2869
- }
2870
- function shallowEqualArray(a, b) {
2871
- if (a === b) return true;
2872
- if (!a || !b) return false;
2873
- if (a.length !== b.length) return false;
2874
- return a.every((val, i) => val === b[i]);
2875
- }
2876
-
2877
- // src/reality/utils/AbortResourceManager.ts
2878
- var AbortResourceManager = class {
2879
- resources = [];
2880
- aborted = false;
2881
- constructor(signal) {
2882
- signal.addEventListener("abort", () => {
2883
- this.aborted = true;
2884
- void this.dispose();
2885
- });
2886
- }
2887
- async addResource(factory) {
2888
- if (this.aborted) throw new DOMException("Aborted", "AbortError");
2889
- const resource = await factory();
2890
- if (this.aborted) {
2891
- await resource.destroy();
2892
- throw new DOMException("Aborted", "AbortError");
2893
- }
2894
- this.resources.push(resource);
2895
- return resource;
2896
- }
2897
- async dispose() {
2898
- const resources = this.resources.splice(0);
2899
- for (const r of resources) {
2900
- try {
2901
- await r.destroy();
2902
- } catch (e) {
2903
- console.error("AbortResourceManager dispose error:", e, r);
2904
- }
2905
- }
2906
- }
2907
- };
2908
-
2909
- // src/reality/hooks/useEntityTransform.tsx
2910
- function useEntityTransform(entity, { position, rotation, scale }) {
2911
- const last = useRef9({});
2912
- useEffect16(() => {
2913
- if (!entity) return;
2914
- const shouldUpdate = !shallowEqualVec3(last.current.position, position) || !shallowEqualRotation(last.current.rotation, rotation) || !shallowEqualVec3(last.current.scale, scale);
2915
- if (!shouldUpdate) return;
2916
- last.current = { position, rotation, scale };
2917
- const updateTransform = async () => {
2918
- try {
2919
- await entity.updateTransform({ position, rotation, scale });
2920
- } catch (err) {
2921
- console.error("[useEntityTransform] Failed to update transform:", err);
2922
- }
2923
- };
2924
- updateTransform();
2925
- return () => {
2926
- };
2927
- }, [entity, position, rotation, scale]);
2928
- }
2929
-
2930
- // src/reality/hooks/useEntityEvent.tsx
2931
- import { useEffect as useEffect17, useRef as useRef10 } from "react";
2932
-
2933
- // src/reality/type.ts
2934
- var eventMap = {
2935
- // tap
2936
- onSpatialTap: "spatialtap",
2937
- // drag
2938
- onSpatialDragStart: "spatialdragstart",
2939
- onSpatialDrag: "spatialdrag",
2940
- onSpatialDragEnd: "spatialdragend",
2941
- // rotate
2942
- onSpatialRotate: "spatialrotate",
2943
- onSpatialRotateEnd: "spatialrotateend",
2944
- // magnify
2945
- onSpatialMagnify: "spatialmagnify",
2946
- onSpatialMagnifyEnd: "spatialmagnifyend"
2947
- };
2948
-
2949
- // src/reality/hooks/useEntityRef.tsx
2950
- import { useImperativeHandle } from "react";
2951
- var useEntityRef = (ref, instance) => {
2952
- useImperativeHandle(ref, () => instance);
2953
- };
2954
- var EntityRef = class {
2955
- _entity;
2956
- _ctx;
2957
- constructor(entity = null, ctx = null) {
2958
- this._entity = entity;
2959
- this._ctx = ctx;
2960
- }
2961
- updateEntity(entity) {
2962
- if (entity) this._entity = entity;
2963
- }
2964
- updateCtx(ctx) {
2965
- if (ctx) this._ctx = ctx;
2966
- }
2967
- destroy() {
2968
- this._entity?.destroy();
2969
- }
2970
- get entity() {
2971
- return this._entity;
2972
- }
2973
- get id() {
2974
- return this._entity?.userData?.id;
2975
- }
2976
- get name() {
2977
- return this._entity?.userData?.name;
2978
- }
2979
- async convertFromEntityToEntity(fromEntityId, toEntityId, position) {
2980
- if (!this._entity) return position;
2981
- try {
2982
- const fromEnt = await this._ctx?.resourceRegistry.get(fromEntityId);
2983
- const toEnt = await this._ctx?.resourceRegistry.get(toEntityId);
2984
- if (!fromEnt || !toEnt) return position;
2985
- const ret = await this._entity.convertFromEntityToEntity(
2986
- fromEnt.id,
2987
- toEnt.id,
2988
- position
2989
- );
2990
- return ret?.data ?? position;
2991
- } catch {
2992
- return position;
2993
- }
2994
- }
2995
- async convertFromEntityToReality(entityId, position) {
2996
- if (!this._entity) return position;
2997
- try {
2998
- const ent = await this._ctx?.resourceRegistry.get(entityId);
2999
- if (!ent) return position;
3000
- const ret = await this._entity.convertFromEntityToScene(ent.id, position);
3001
- return ret?.data ?? position;
3002
- } catch {
3003
- return position;
3004
- }
3005
- }
3006
- async convertFromRealityToEntity(entityId, position) {
3007
- if (!this._entity) return position;
3008
- try {
3009
- const ent = await this._ctx?.resourceRegistry.get(entityId);
3010
- if (!ent) return position;
3011
- const ret = await this._entity.convertFromSceneToEntity(ent.id, position);
3012
- return ret?.data ?? position;
3013
- } catch {
3014
- return position;
3015
- }
3016
- }
3017
- };
3018
-
3019
- // src/reality/hooks/useEntityEvent.tsx
3020
- function createEventProxy2(ev, instance) {
3021
- return new Proxy(ev, {
3022
- get(target, prop) {
3023
- if (prop === "currentTarget") {
3024
- return instance;
3025
- }
3026
- if (prop === "target") {
3027
- const origin = target.__origin;
3028
- if (origin) {
3029
- return new EntityRef(origin, null);
3030
- }
3031
- return instance;
3032
- }
3033
- if (prop === "bubbles") {
3034
- return true;
3035
- }
3036
- if (prop === "offsetX") {
3037
- const type = target.type;
3038
- if (type === "spatialtap") {
3039
- return target.detail?.location3D?.x ?? 0;
3040
- }
3041
- if (type === "spatialdragstart") {
3042
- return target.detail?.startLocation3D?.x ?? 0;
3043
- }
3044
- return void 0;
3045
- }
3046
- if (prop === "offsetY") {
3047
- const type = target.type;
3048
- if (type === "spatialtap") {
3049
- return target.detail?.location3D?.y ?? 0;
3050
- }
3051
- if (type === "spatialdragstart") {
3052
- return target.detail?.startLocation3D?.y ?? 0;
3053
- }
3054
- return void 0;
3055
- }
3056
- if (prop === "offsetZ") {
3057
- const type = target.type;
3058
- if (type === "spatialtap") {
3059
- return target.detail?.location3D?.z ?? 0;
3060
- }
3061
- if (type === "spatialdragstart") {
3062
- return target.detail?.startLocation3D?.z ?? 0;
3063
- }
3064
- return void 0;
3065
- }
3066
- if (prop === "translationX") {
3067
- const type = target.type;
3068
- if (type === "spatialdrag") {
3069
- return target.detail?.translation3D?.x ?? 0;
3070
- }
3071
- return void 0;
3072
- }
3073
- if (prop === "translationY") {
3074
- const type = target.type;
3075
- if (type === "spatialdrag") {
3076
- return target.detail?.translation3D?.y ?? 0;
3077
- }
3078
- return void 0;
3079
- }
3080
- if (prop === "translationZ") {
3081
- const type = target.type;
3082
- if (type === "spatialdrag") {
3083
- return target.detail?.translation3D?.z ?? 0;
3084
- }
3085
- return void 0;
3086
- }
3087
- if (prop === "quaternion") {
3088
- const type = target.type;
3089
- if (type === "spatialrotate") {
3090
- return target.detail?.quaternion ?? {
3091
- x: 0,
3092
- y: 0,
3093
- z: 0,
3094
- w: 1
3095
- };
3096
- }
3097
- return void 0;
3098
- }
3099
- if (prop === "magnification") {
3100
- const type = target.type;
3101
- if (type === "spatialmagnify") {
3102
- return target.detail?.magnification ?? 1;
3103
- }
3104
- return void 0;
3105
- }
3106
- if (prop === "clientX") {
3107
- const type = target.type;
3108
- if (type === "spatialtap" || type === "spatialdragstart") {
3109
- return target.detail?.globalLocation3D?.x ?? 0;
3110
- }
3111
- return void 0;
3112
- }
3113
- if (prop === "clientY") {
3114
- const type = target.type;
3115
- if (type === "spatialtap" || type === "spatialdragstart") {
3116
- return target.detail?.globalLocation3D?.y ?? 0;
3117
- }
3118
- return void 0;
3119
- }
3120
- if (prop === "clientZ") {
3121
- const type = target.type;
3122
- if (type === "spatialtap" || type === "spatialdragstart") {
3123
- return target.detail?.globalLocation3D?.z ?? 0;
3124
- }
3125
- return void 0;
3126
- }
3127
- const val = target[prop];
3128
- return typeof val === "function" ? val.bind(target) : val;
3129
- }
3130
- });
3131
- }
3132
- var useEntityEvent = ({ instance, ...handlers }) => {
3133
- const eventsSetRef = useRef10(/* @__PURE__ */ new Set());
3134
- useEffect17(() => {
3135
- const entity = instance.entity;
3136
- if (!entity) return;
3137
- Object.entries(eventMap).forEach(([reactKey, spatialEvent]) => {
3138
- const handlerFn = handlers[reactKey];
3139
- if (!handlerFn) return;
3140
- const wrapped = (ev) => handlerFn(createEventProxy2(ev, instance));
3141
- entity.addEvent(spatialEvent, wrapped);
3142
- eventsSetRef.current.add(reactKey);
3143
- });
3144
- return () => {
3145
- };
3146
- }, [instance.entity, ...Object.values(handlers)]);
3147
- useEffect17(() => {
3148
- const entity = instance.entity;
3149
- if (!entity) return;
3150
- return () => {
3151
- for (let x of eventsSetRef.current) {
3152
- entity.removeEvent(x);
3153
- }
3154
- eventsSetRef.current.clear();
3155
- };
3156
- }, [instance.entity]);
3157
- return null;
3158
- };
3159
-
3160
- // src/reality/hooks/useRealityEvents.tsx
3161
- import { useEffect as useEffect18, useRef as useRef11 } from "react";
3162
- function createEventProxy3(ev, instance) {
3163
- return new Proxy(ev, {
3164
- get(target, prop) {
3165
- if (prop === "currentTarget") {
3166
- return instance;
3167
- }
3168
- if (prop === "target") {
3169
- const origin = target.__origin;
3170
- if (origin) {
3171
- return new EntityRef(origin, null);
3172
- }
3173
- return instance;
3174
- }
3175
- if (prop === "bubbles") {
3176
- return true;
3177
- }
3178
- if (prop === "offsetX") {
3179
- const type = target.type;
3180
- if (type === "spatialtap") {
3181
- return target.detail?.location3D?.x ?? 0;
3182
- }
3183
- if (type === "spatialdragstart") {
3184
- return target.detail?.startLocation3D?.x ?? 0;
3185
- }
3186
- return void 0;
3187
- }
3188
- if (prop === "offsetY") {
3189
- const type = target.type;
3190
- if (type === "spatialtap") {
3191
- return target.detail?.location3D?.y ?? 0;
3192
- }
3193
- if (type === "spatialdragstart") {
3194
- return target.detail?.startLocation3D?.y ?? 0;
3195
- }
3196
- return void 0;
3197
- }
3198
- if (prop === "offsetZ") {
3199
- const type = target.type;
3200
- if (type === "spatialtap") {
3201
- return target.detail?.location3D?.z ?? 0;
3202
- }
3203
- if (type === "spatialdragstart") {
3204
- return target.detail?.startLocation3D?.z ?? 0;
3205
- }
3206
- return void 0;
3207
- }
3208
- if (prop === "translationX") {
3209
- const type = target.type;
3210
- if (type === "spatialdrag") {
3211
- return target.detail?.translation3D?.x ?? 0;
3212
- }
3213
- return void 0;
3214
- }
3215
- if (prop === "translationY") {
3216
- const type = target.type;
3217
- if (type === "spatialdrag") {
3218
- return target.detail?.translation3D?.y ?? 0;
3219
- }
3220
- return void 0;
3221
- }
3222
- if (prop === "translationZ") {
3223
- const type = target.type;
3224
- if (type === "spatialdrag") {
3225
- return target.detail?.translation3D?.z ?? 0;
3226
- }
3227
- return void 0;
3228
- }
3229
- if (prop === "quaternion") {
3230
- const type = target.type;
3231
- if (type === "spatialrotate") {
3232
- return target.detail?.quaternion ?? {
3233
- x: 0,
3234
- y: 0,
3235
- z: 0,
3236
- w: 1
3237
- };
3238
- }
3239
- return void 0;
3240
- }
3241
- if (prop === "magnification") {
3242
- const type = target.type;
3243
- if (type === "spatialmagnify") {
3244
- return target.detail?.magnification ?? 1;
3245
- }
3246
- return void 0;
3247
- }
3248
- if (prop === "clientX") {
3249
- const type = target.type;
3250
- if (type === "spatialtap" || type === "spatialdragstart") {
3251
- return target.detail?.globalLocation3D?.x ?? 0;
3252
- }
3253
- return void 0;
3254
- }
3255
- if (prop === "clientY") {
3256
- const type = target.type;
3257
- if (type === "spatialtap" || type === "spatialdragstart") {
3258
- return target.detail?.globalLocation3D?.y ?? 0;
3259
- }
3260
- return void 0;
3261
- }
3262
- if (prop === "clientZ") {
3263
- const type = target.type;
3264
- if (type === "spatialtap" || type === "spatialdragstart") {
3265
- return target.detail?.globalLocation3D?.z ?? 0;
3266
- }
3267
- return void 0;
3268
- }
3269
- const val = target[prop];
3270
- return typeof val === "function" ? val.bind(target) : val;
3271
- }
3272
- });
3273
- }
3274
- var useRealityEvents = ({ instance, ...handlers }) => {
3275
- const eventsSetRef = useRef11(/* @__PURE__ */ new Set());
3276
- useEffect18(() => {
3277
- if (!instance) return;
3278
- Object.entries(eventMap).forEach(([reactKey, spatialEvent]) => {
3279
- const handlerFn = handlers[reactKey];
3280
- if (!handlerFn) return;
3281
- const wrapped = (ev) => handlerFn(createEventProxy3(ev, instance));
3282
- instance.addEvent(spatialEvent, wrapped);
3283
- eventsSetRef.current.add(spatialEvent);
3284
- });
3285
- return () => {
3286
- if (instance) {
3287
- for (let x of eventsSetRef.current) {
3288
- instance.removeEvent(x);
3289
- }
3290
- eventsSetRef.current.clear();
3291
- }
3292
- };
3293
- }, [instance, ...Object.values(handlers)]);
3294
- };
3295
-
3296
- // src/reality/hooks/useEntityId.tsx
3297
- import { useEffect as useEffect19 } from "react";
3298
- var useEntityId = ({ id, entity }) => {
3299
- const ctx = useRealityContext();
3300
- useEffect19(() => {
3301
- if (!id || !entity || !ctx) return;
3302
- ctx.resourceRegistry.add(id, Promise.resolve(entity));
3303
- return () => {
3304
- ctx.resourceRegistry.remove(id);
3305
- };
3306
- }, [id, entity, ctx]);
3307
- return null;
3308
- };
3309
-
3310
- // src/reality/hooks/useEntity.tsx
3311
- import { useEffect as useEffect20, useRef as useRef12 } from "react";
3312
- var useEntity = ({
3313
- ref,
3314
- id,
3315
- position,
3316
- rotation,
3317
- scale,
3318
- enableInput,
3319
- onSpatialTap,
3320
- onSpatialDragStart,
3321
- onSpatialDrag,
3322
- onSpatialDragEnd,
3323
- onSpatialRotate,
3324
- onSpatialRotateEnd,
3325
- onSpatialMagnify,
3326
- onSpatialMagnifyEnd,
3327
- createEntity,
3328
- recreateKey
3329
- }) => {
3330
- const ctx = useRealityContext();
3331
- const parent = useParentContext();
3332
- const instanceRef = useRef12(new EntityRef(null, ctx));
3333
- const forceUpdate = useForceUpdate2();
3334
- useEffect20(() => {
3335
- if (!ctx) return;
3336
- const controller = new AbortController();
3337
- const init = async () => {
3338
- try {
3339
- const ent = await createEntity(controller.signal);
3340
- if (!ent) return;
3341
- if (controller.signal.aborted) {
3342
- ent.destroy();
3343
- return;
3344
- }
3345
- await ent.updateTransform({ position, rotation, scale });
3346
- if (controller.signal.aborted) {
3347
- ent.destroy();
3348
- return;
3349
- }
3350
- if (parent) {
3351
- const result = await parent.addEntity(ent);
3352
- if (!result.success) throw new Error("parent.addEntity failed");
3353
- } else {
3354
- const result = await ctx.reality.addEntity(ent);
3355
- if (!result.success) throw new Error("ctx.reality.addEntity failed");
3356
- }
3357
- instanceRef.current?.updateEntity(ent);
3358
- forceUpdate();
3359
- } catch (error) {
3360
- console.error("useEntity init ~ error:", error);
3361
- }
3362
- };
3363
- init();
3364
- return () => {
3365
- controller.abort();
3366
- instanceRef.current?.destroy();
3367
- };
3368
- }, [ctx, parent, recreateKey]);
3369
- useEntityId({ id, entity: instanceRef.current.entity });
3370
- useEntityTransform(instanceRef.current.entity, { position, rotation, scale });
3371
- useEntityRef(ref, instanceRef.current);
3372
- useEntityEvent({
3373
- instance: instanceRef.current,
3374
- onSpatialTap,
3375
- onSpatialDragStart,
3376
- onSpatialDrag,
3377
- onSpatialDragEnd,
3378
- onSpatialRotate,
3379
- onSpatialRotateEnd,
3380
- onSpatialMagnify,
3381
- onSpatialMagnifyEnd
3382
- });
3383
- useEffect20(() => {
3384
- const ent = instanceRef.current.entity;
3385
- if (!ent) return;
3386
- if (enableInput !== void 0) {
3387
- ent.enableInput = !!enableInput;
3388
- }
3389
- }, [instanceRef.current.entity, enableInput]);
3390
- return instanceRef.current.entity;
3391
- };
3392
-
3393
- // src/reality/hooks/useForceUpdate.tsx
3394
- import { useCallback as useCallback9, useState as useState9 } from "react";
3395
- var useForceUpdate2 = () => {
3396
- const [, setTick] = useState9(0);
3397
- return useCallback9(() => setTick((tick) => tick + 1), []);
3398
- };
3399
-
3400
- // src/reality/components/BaseEntity.tsx
3401
- import { jsx as jsx12 } from "react/jsx-runtime";
3402
- var BaseEntity = forwardRef10(
3403
- ({ children, createEntity, recreateKey, ...rest }, ref) => {
3404
- const ctx = useRealityContext();
3405
- const entity = useEntity({
3406
- ...rest,
3407
- ref,
3408
- recreateKey,
3409
- createEntity: (signal) => createEntity(ctx, signal)
3410
- });
3411
- if (!entity) return null;
3412
- return /* @__PURE__ */ jsx12(ParentContext.Provider, { value: entity, children });
3413
- }
3414
- );
3415
-
3416
- // src/reality/components/Entity.tsx
3417
- import { jsx as jsx13 } from "react/jsx-runtime";
3418
- var Entity = forwardRef11((props, ref) => {
3419
- const { id, name, children, ...rest } = props;
3420
- return /* @__PURE__ */ jsx13(
3421
- BaseEntity,
3422
- {
3423
- ...rest,
3424
- id,
3425
- ref,
3426
- createEntity: async (ctxVal) => ctxVal.session.createEntity({ id, name }),
3427
- children
3428
- }
3429
- );
3430
- });
3431
-
3432
- // src/reality/components/BoxEntity.tsx
3433
- import { forwardRef as forwardRef13 } from "react";
3434
-
3435
- // src/reality/components/GeometryEntity.tsx
3436
- import { forwardRef as forwardRef12, useEffect as useEffect21, useRef as useRef13 } from "react";
3437
- import { jsx as jsx14 } from "react/jsx-runtime";
3438
- var GeometryEntity = forwardRef12(
3439
- ({ id, children, name, materials, geometryOptions, createGeometry, ...rest }, ref) => {
3440
- const ctx = useRealityContext();
3441
- const entityRef = useRef13(null);
3442
- const componentRef = useRef13(null);
3443
- const mutableRef = useRef13({
3444
- lastSnapshot: null,
3445
- rebuildGen: 0
3446
- });
3447
- useEffect21(() => {
3448
- const { lastSnapshot } = mutableRef.current;
3449
- if (!ctx || !entityRef.current || lastSnapshot === null) return;
3450
- const geometryChanged = !shallowEqualObject(
3451
- lastSnapshot.geometryOptions,
3452
- geometryOptions
3453
- );
3454
- const materialsChanged = !shallowEqualArray(
3455
- lastSnapshot.materials,
3456
- materials
3457
- );
3458
- if (!geometryChanged && !materialsChanged) return;
3459
- mutableRef.current.lastSnapshot = { geometryOptions, materials };
3460
- mutableRef.current.rebuildGen += 1;
3461
- const gen = mutableRef.current.rebuildGen;
3462
- const rebuild = async () => {
3463
- const entity = entityRef.current;
3464
- if (!entity) return;
3465
- try {
3466
- const oldComponent = componentRef.current;
3467
- if (oldComponent) {
3468
- await entity.removeComponent(oldComponent);
3469
- await oldComponent.destroy();
3470
- componentRef.current = null;
3471
- if (gen !== mutableRef.current.rebuildGen) return;
3472
- }
3473
- const geometry = await createGeometry(geometryOptions);
3474
- if (gen !== mutableRef.current.rebuildGen) {
3475
- await geometry.destroy();
3476
- return;
3477
- }
3478
- const materialList = await Promise.all(
3479
- materials?.map((mid) => ctx.resourceRegistry.get(mid)).filter(Boolean) ?? []
3480
- );
3481
- if (gen !== mutableRef.current.rebuildGen) {
3482
- await geometry.destroy();
3483
- return;
3484
- }
3485
- const modelComponent = await ctx.session.createModelComponent({
3486
- mesh: geometry,
3487
- materials: materialList
3488
- });
3489
- if (gen !== mutableRef.current.rebuildGen) {
3490
- await modelComponent.destroy();
3491
- await geometry.destroy();
3492
- return;
3493
- }
3494
- await entity.addComponent(modelComponent);
3495
- componentRef.current = modelComponent;
3496
- } catch (error) {
3497
- if (gen === mutableRef.current.rebuildGen) {
3498
- console.error("GeometryEntity: rebuild failed", error);
3499
- }
3500
- }
3501
- };
3502
- rebuild();
3503
- }, [ctx, geometryOptions, materials, createGeometry]);
3504
- return /* @__PURE__ */ jsx14(
3505
- BaseEntity,
3506
- {
3507
- ...rest,
3508
- id,
3509
- ref,
3510
- createEntity: async (ctx2, signal) => {
3511
- const manager = new AbortResourceManager(signal);
3512
- try {
3513
- const ent = await manager.addResource(
3514
- () => ctx2.session.createEntity({ id, name })
3515
- );
3516
- const geometry = await manager.addResource(
3517
- () => createGeometry(geometryOptions)
3518
- );
3519
- const materialList = await Promise.all(
3520
- materials?.map((id2) => ctx2.resourceRegistry.get(id2)).filter(Boolean) ?? []
3521
- );
3522
- const modelComponent = await manager.addResource(
3523
- () => ctx2.session.createModelComponent({
3524
- mesh: geometry,
3525
- materials: materialList
3526
- })
3527
- );
3528
- await ent.addComponent(modelComponent);
3529
- entityRef.current = ent;
3530
- componentRef.current = modelComponent;
3531
- mutableRef.current.lastSnapshot = { geometryOptions, materials };
3532
- return ent;
3533
- } catch (error) {
3534
- await manager.dispose();
3535
- return null;
3536
- }
3537
- },
3538
- children
3539
- }
3540
- );
3541
- }
3542
- );
3543
-
3544
- // src/reality/components/BoxEntity.tsx
3545
- import { jsx as jsx15 } from "react/jsx-runtime";
3546
- var BoxEntity = forwardRef13(
3547
- ({ children, ...props }, ref) => {
3548
- const ctx = useRealityContext();
3549
- return /* @__PURE__ */ jsx15(
3550
- GeometryEntity,
3551
- {
3552
- ...props,
3553
- ref,
3554
- createGeometry: (options) => ctx.session.createBoxGeometry(options),
3555
- geometryOptions: {
3556
- width: props.width,
3557
- height: props.height,
3558
- depth: props.depth,
3559
- cornerRadius: props.cornerRadius,
3560
- splitFaces: props.splitFaces
3561
- },
3562
- children
3563
- }
3564
- );
3565
- }
3566
- );
3567
-
3568
- // src/reality/components/UnlitMaterial.tsx
3569
- import { useEffect as useEffect22, useRef as useRef14, useState as useState10 } from "react";
3570
- var UnlitMaterial = ({
3571
- children,
3572
- ...options
3573
- }) => {
3574
- const ctx = useRealityContext();
3575
- const materialRef = useRef14(void 0);
3576
- const isInitializedRef = useRef14(false);
3577
- const [textureRevision, setTextureRevision] = useState10(0);
3578
- useEffect22(() => {
3579
- if (!ctx || !options.textureId) return;
3580
- return ctx.resourceRegistry.subscribe(options.textureId, () => {
3581
- setTextureRevision((v) => v + 1);
3582
- });
3583
- }, [ctx, options.textureId]);
3584
- useEffect22(() => {
3585
- if (!ctx) return;
3586
- let cancelled = false;
3587
- const materialId = options.id;
3588
- const { session, resourceRegistry } = ctx;
3589
- const init = async () => {
3590
- try {
3591
- let textureIdForNative = options.textureId;
3592
- if (options.textureId) {
3593
- const texturePromise = resourceRegistry.get(options.textureId);
3594
- try {
3595
- const textureResource = await texturePromise;
3596
- if (cancelled) return;
3597
- textureIdForNative = textureResource.id;
3598
- } catch {
3599
- textureIdForNative = "";
3600
- }
3601
- }
3602
- if (cancelled) return;
3603
- const commandOptions = {
3604
- color: options.color,
3605
- textureId: textureIdForNative,
3606
- transparent: options.transparent,
3607
- opacity: options.opacity
3608
- };
3609
- const materialPromise = session.createUnlitMaterial(commandOptions);
3610
- resourceRegistry.add(materialId, materialPromise);
3611
- const mat = await materialPromise;
3612
- if (cancelled) return;
3613
- materialRef.current = mat;
3614
- isInitializedRef.current = true;
3615
- } catch (error) {
3616
- console.error(" ~ UnlitMaterial ~ error:", error);
3617
- }
3618
- };
3619
- init();
3620
- return () => {
3621
- cancelled = true;
3622
- resourceRegistry.removeAndDestroy(materialId);
3623
- materialRef.current = void 0;
3624
- isInitializedRef.current = false;
3625
- };
3626
- }, [ctx, options.id]);
3627
- useEffect22(() => {
3628
- if (!ctx || !isInitializedRef.current || !materialRef.current) return;
3629
- let cancelled = false;
3630
- void (async () => {
3631
- const updates = {};
3632
- if (options.color !== void 0) updates.color = options.color;
3633
- if (options.transparent !== void 0)
3634
- updates.transparent = options.transparent;
3635
- if (options.opacity !== void 0) updates.opacity = options.opacity;
3636
- if (options.textureId !== void 0) {
3637
- if (options.textureId === "") {
3638
- updates.textureId = "";
3639
- } else {
3640
- const texturePromise = ctx.resourceRegistry.get(options.textureId);
3641
- try {
3642
- const textureResource = await texturePromise;
3643
- if (cancelled) return;
3644
- updates.textureId = textureResource.id;
3645
- } catch {
3646
- updates.textureId = "";
3647
- }
3648
- }
3649
- }
3650
- if (cancelled || Object.keys(updates).length === 0) return;
3651
- const mat = materialRef.current;
3652
- if (mat) {
3653
- void mat.updateProperties(updates).catch(() => {
3654
- });
3655
- }
3656
- })();
3657
- return () => {
3658
- cancelled = true;
3659
- };
3660
- }, [
3661
- ctx,
3662
- options.color,
3663
- options.textureId,
3664
- options.transparent,
3665
- options.opacity,
3666
- textureRevision
3667
- ]);
3668
- return null;
3669
- };
3670
-
3671
- // src/reality/components/Texture.tsx
3672
- import { useEffect as useEffect23, useRef as useRef15 } from "react";
3673
- var Texture = ({
3674
- children,
3675
- id,
3676
- url,
3677
- onLoad,
3678
- onError
3679
- }) => {
3680
- const ctx = useRealityContext();
3681
- const textureRef = useRef15(null);
3682
- const urlRevisionRef = useRef15(0);
3683
- useEffect23(() => {
3684
- if (!ctx) return;
3685
- const { resourceRegistry } = ctx;
3686
- const capturedId = id;
3687
- return () => {
3688
- textureRef.current = null;
3689
- resourceRegistry.removeAndDestroy(capturedId);
3690
- };
3691
- }, [ctx, id]);
3692
- useEffect23(() => {
3693
- if (!ctx) return;
3694
- const { session, resourceRegistry } = ctx;
3695
- const revision = ++urlRevisionRef.current;
3696
- let cancelled = false;
3697
- void (async () => {
3698
- const resolvedUrl = getAbsoluteUrl(url);
3699
- try {
3700
- if (textureRef.current) {
3701
- await textureRef.current.updateProperties({ url: resolvedUrl });
3702
- if (cancelled || revision !== urlRevisionRef.current) return;
3703
- resourceRegistry.notify(id);
3704
- onLoad?.();
3705
- return;
3706
- }
3707
- const texturePromise = session.createTexture({ url: resolvedUrl });
3708
- resourceRegistry.add(id, texturePromise);
3709
- const tex = await texturePromise;
3710
- if (cancelled || revision !== urlRevisionRef.current) {
3711
- tex.destroy();
3712
- return;
3713
- }
3714
- textureRef.current = tex;
3715
- onLoad?.();
3716
- } catch (error) {
3717
- if (cancelled || revision !== urlRevisionRef.current) return;
3718
- onError?.(error);
3719
- }
3720
- })();
3721
- return () => {
3722
- cancelled = true;
3723
- };
3724
- }, [ctx, id, url]);
3725
- return null;
3726
- };
3727
-
3728
- // src/reality/components/SphereEntity.tsx
3729
- import { forwardRef as forwardRef14 } from "react";
3730
- import { jsx as jsx16 } from "react/jsx-runtime";
3731
- var SphereEntity = forwardRef14(
3732
- ({ children, ...props }, ref) => {
3733
- const ctx = useRealityContext();
3734
- return /* @__PURE__ */ jsx16(
3735
- GeometryEntity,
3736
- {
3737
- ...props,
3738
- ref,
3739
- createGeometry: (options) => ctx.session.createSphereGeometry(options),
3740
- geometryOptions: {
3741
- radius: props.radius
3742
- },
3743
- children
3744
- }
3745
- );
3746
- }
3747
- );
3748
-
3749
- // src/reality/components/ConeEntity.tsx
3750
- import { forwardRef as forwardRef15 } from "react";
3751
- import { jsx as jsx17 } from "react/jsx-runtime";
3752
- var ConeEntity = forwardRef15(
3753
- ({ children, ...props }, ref) => {
3754
- const ctx = useRealityContext();
3755
- return /* @__PURE__ */ jsx17(
3756
- GeometryEntity,
3757
- {
3758
- ...props,
3759
- ref,
3760
- createGeometry: (options) => ctx.session.createConeGeometry(options),
3761
- geometryOptions: {
3762
- radius: props.radius,
3763
- height: props.height
3764
- },
3765
- children
3766
- }
3767
- );
3768
- }
3769
- );
3770
-
3771
- // src/reality/components/CylinderEntity.tsx
3772
- import { forwardRef as forwardRef16 } from "react";
3773
- import { jsx as jsx18 } from "react/jsx-runtime";
3774
- var CylinderEntity = forwardRef16(
3775
- ({ children, ...props }, ref) => {
3776
- const ctx = useRealityContext();
3777
- return /* @__PURE__ */ jsx18(
3778
- GeometryEntity,
3779
- {
3780
- ...props,
3781
- ref,
3782
- createGeometry: (options) => ctx.session.createCylinderGeometry(options),
3783
- geometryOptions: {
3784
- radius: props.radius,
3785
- height: props.height
3786
- },
3787
- children
3788
- }
3789
- );
3790
- }
3791
- );
3792
-
3793
- // src/reality/components/PlaneEntity.tsx
3794
- import { forwardRef as forwardRef17 } from "react";
3795
- import { jsx as jsx19 } from "react/jsx-runtime";
3796
- var PlaneEntity = forwardRef17(
3797
- ({ children, ...props }, ref) => {
3798
- const ctx = useRealityContext();
3799
- return /* @__PURE__ */ jsx19(
3800
- GeometryEntity,
3801
- {
3802
- ...props,
3803
- ref,
3804
- createGeometry: (options) => ctx.session.createPlaneGeometry(options),
3805
- geometryOptions: {
3806
- width: props.width,
3807
- height: props.height,
3808
- cornerRadius: props.cornerRadius
3809
- },
3810
- children
3811
- }
3812
- );
3813
- }
3814
- );
3815
-
3816
- // src/reality/components/SceneGraph.tsx
3817
- import { jsx as jsx20 } from "react/jsx-runtime";
3818
- var SceneGraph = ({ children }) => {
3819
- return /* @__PURE__ */ jsx20(ParentContext.Provider, { value: null, children });
3820
- };
3821
-
3822
- // src/reality/components/ModelAsset.tsx
3823
- import { useEffect as useEffect24, useRef as useRef16 } from "react";
3824
- var ModelAsset = ({ children, ...options }) => {
3825
- const ctx = useRealityContext();
3826
- const materialRef = useRef16(void 0);
3827
- useEffect24(() => {
3828
- const controller = new AbortController();
3829
- if (!ctx) return;
3830
- const { session, resourceRegistry } = ctx;
3831
- const init = async () => {
3832
- try {
3833
- const resolvedUrl = getAbsoluteUrl(options.src);
3834
- const modelAssetPromise = session.createModelAsset({ url: resolvedUrl });
3835
- resourceRegistry.add(options.id, modelAssetPromise);
3836
- const mat = await modelAssetPromise;
3837
- if (controller.signal.aborted) {
3838
- mat.destroy();
3839
- return;
3840
- }
3841
- materialRef.current = mat;
3842
- options.onLoad?.();
3843
- } catch (error) {
3844
- options.onError?.(error);
3845
- }
3846
- };
3847
- init();
3848
- return () => {
3849
- controller.abort();
3850
- materialRef.current?.destroy();
3851
- };
3852
- }, [ctx]);
3853
- return null;
3854
- };
3855
-
3856
- // src/reality/components/ModelEntity.tsx
3857
- import { forwardRef as forwardRef18, useEffect as useEffect25, useRef as useRef17 } from "react";
3858
- import { jsx as jsx21 } from "react/jsx-runtime";
3859
- var ModelEntity = forwardRef18(
3860
- ({ id, model, children, name, materials, ...rest }, ref) => {
3861
- const ctx = useRealityContext();
3862
- const entityRef = useRef17(null);
3863
- const lastMaterialsRef = useRef17(void 0);
3864
- useEffect25(() => {
3865
- if (!ctx || !entityRef.current) return;
3866
- const next = materials ?? [];
3867
- const prev = lastMaterialsRef.current ?? [];
3868
- if (shallowEqualArray(prev, next)) return;
3869
- lastMaterialsRef.current = next;
3870
- const apply = async () => {
3871
- try {
3872
- const materialList = (await Promise.all(next.map((mid) => ctx.resourceRegistry.get(mid)))).filter(Boolean);
3873
- if (entityRef.current) {
3874
- await entityRef.current.setMaterials(materialList);
3875
- }
3876
- } catch (error) {
3877
- console.error("ModelEntity: failed to set materials", error);
3878
- }
3879
- };
3880
- apply();
3881
- }, [ctx, materials]);
3882
- return /* @__PURE__ */ jsx21(
3883
- BaseEntity,
3884
- {
3885
- ...rest,
3886
- id,
3887
- ref,
3888
- recreateKey: model,
3889
- createEntity: async (ctx2, signal) => {
3890
- try {
3891
- const modelAsset = await ctx2.resourceRegistry.get(model);
3892
- if (!modelAsset)
3893
- throw new Error(`ModelEntity: model not found ${model}`);
3894
- if (signal.aborted) return null;
3895
- const ent = await ctx2.session.createSpatialModelEntity(
3896
- {
3897
- modelAssetId: modelAsset.id,
3898
- name
3899
- },
3900
- { id, name }
3901
- );
3902
- entityRef.current = ent;
3903
- if (materials && materials.length > 0) {
3904
- const materialList = (await Promise.all(
3905
- materials.map((mid) => ctx2.resourceRegistry.get(mid))
3906
- )).filter(Boolean);
3907
- if (materialList.length > 0 && !signal.aborted) {
3908
- await ent.setMaterials(materialList);
3909
- }
3910
- }
3911
- lastMaterialsRef.current = materials ?? [];
3912
- return ent;
3913
- } catch (error) {
3914
- return null;
3915
- }
3916
- },
3917
- children
3918
- }
3919
- );
3920
- }
3921
- );
3922
-
3923
- // src/reality/components/Reality.tsx
3924
- import {
3925
- forwardRef as forwardRef19,
3926
- useCallback as useCallback10,
3927
- useEffect as useEffect26,
3928
- useRef as useRef18,
3929
- useState as useState11
3930
- } from "react";
3931
- import { Fragment as Fragment3, jsx as jsx22, jsxs as jsxs3 } from "react/jsx-runtime";
3932
- var Reality = forwardRef19(
3933
- function RealityBase({ children, ...inProps }, ref) {
3934
- const insideAttachment = useInsideAttachment();
3935
- if (insideAttachment) {
3936
- console.warn(
3937
- "[WebSpatial] Reality cannot be used inside AttachmentAsset."
3938
- );
3939
- return null;
3940
- }
3941
- const {
3942
- onSpatialTap,
3943
- onSpatialDragStart,
3944
- onSpatialDrag,
3945
- onSpatialDragEnd,
3946
- onSpatialRotate,
3947
- onSpatialRotateEnd,
3948
- onSpatialMagnify,
3949
- onSpatialMagnifyEnd,
3950
- ...props
3951
- } = inProps;
3952
- const ctxRef = useRef18(null);
3953
- const creationId = useRef18(0);
3954
- const [isReady, setIsReady] = useState11(false);
3955
- const cleanupReality = useCallback10(() => {
3956
- ctxRef.current?.attachmentRegistry.destroy();
3957
- ctxRef.current?.resourceRegistry.destroy();
3958
- ctxRef.current?.reality.destroy();
3959
- ctxRef.current = null;
3960
- setIsReady(false);
3961
- }, []);
3962
- useEffect26(() => {
3963
- return () => {
3964
- creationId.current++;
3965
- cleanupReality();
3966
- };
3967
- }, [cleanupReality]);
3968
- const createReality = useCallback10(async () => {
3969
- const id = ++creationId.current;
3970
- const resourceRegistry = new ResourceRegistry();
3971
- const attachmentRegistry = new AttachmentRegistry();
3972
- const session = await getSession();
3973
- if (!session) {
3974
- resourceRegistry.destroy();
3975
- attachmentRegistry.destroy();
3976
- return null;
3977
- }
3978
- const reality = await session.createSpatializedDynamic3DElement();
3979
- const isCancelled = () => id !== creationId.current;
3980
- if (isCancelled()) {
3981
- resourceRegistry.destroy();
3982
- attachmentRegistry.destroy();
3983
- reality.destroy();
3984
- return null;
3985
- }
3986
- try {
3987
- const result = await session.getSpatialScene().addSpatializedElement(reality);
3988
- if (!result.success || isCancelled()) {
3989
- resourceRegistry.destroy();
3990
- attachmentRegistry.destroy();
3991
- reality.destroy();
3992
- return null;
3993
- }
3994
- cleanupReality();
3995
- ctxRef.current = {
3996
- session,
3997
- reality,
3998
- resourceRegistry,
3999
- attachmentRegistry
4000
- };
4001
- setIsReady(true);
4002
- return reality;
4003
- } catch (err) {
4004
- console.error("[createReality] failed", err);
4005
- resourceRegistry.destroy();
4006
- attachmentRegistry.destroy();
4007
- reality.destroy();
4008
- return null;
4009
- }
4010
- }, [cleanupReality]);
4011
- const content = useCallback10(() => /* @__PURE__ */ jsx22(Fragment3, {}), []);
4012
- useRealityEvents({
4013
- instance: ctxRef.current?.reality ?? null,
4014
- onSpatialTap,
4015
- onSpatialDragStart,
4016
- onSpatialDrag,
4017
- onSpatialDragEnd,
4018
- onSpatialRotate,
4019
- onSpatialRotateEnd,
4020
- onSpatialMagnify,
4021
- onSpatialMagnifyEnd
4022
- });
4023
- return /* @__PURE__ */ jsxs3(RealityContext.Provider, { value: ctxRef.current, children: [
4024
- /* @__PURE__ */ jsx22(
4025
- SpatializedContainer,
4026
- {
4027
- component: "div",
4028
- ref,
4029
- createSpatializedElement: createReality,
4030
- spatializedContent: content,
4031
- ...props
4032
- }
4033
- ),
4034
- isReady && children
4035
- ] });
4036
- }
4037
- );
4038
-
4039
- // src/reality/components/AttachmentAsset.tsx
4040
- import { useEffect as useEffect27, useState as useState12 } from "react";
4041
- import { createPortal as createPortal3 } from "react-dom";
4042
- import { jsx as jsx23 } from "react/jsx-runtime";
4043
- var AttachmentAsset = ({
4044
- name,
4045
- children
4046
- }) => {
4047
- const ctx = useRealityContext();
4048
- const [containers, setContainers] = useState12([]);
4049
- useEffect27(() => {
4050
- if (!ctx) return;
4051
- return ctx.attachmentRegistry.onContainersChange(name, setContainers);
4052
- }, [ctx, name]);
4053
- if (!containers.length) return null;
4054
- return /* @__PURE__ */ jsx23(InsideAttachmentContext.Provider, { value: true, children: containers.map(
4055
- ({ instanceId, container }) => createPortal3(children, container, instanceId)
4056
- ) });
4057
- };
4058
-
4059
- // src/reality/components/AttachmentEntity.tsx
4060
- import { useEffect as useEffect28, useRef as useRef19, useState as useState13 } from "react";
4061
- var instanceCounter = 0;
4062
- var AttachmentEntity = ({
4063
- attachment: attachmentName,
4064
- position,
4065
- size
4066
- }) => {
4067
- const ctx = useRealityContext();
4068
- const parent = useParentContext();
4069
- const attachmentRef = useRef19(null);
4070
- const parentIdRef = useRef19(null);
4071
- const instanceIdRef = useRef19(`att_${++instanceCounter}`);
4072
- const attachmentNameRef = useRef19(attachmentName);
4073
- const [childWindow, setChildWindow] = useState13(null);
4074
- useEffect28(() => {
4075
- if (!ctx || !parent) return;
4076
- if (attachmentRef.current) return;
4077
- const parentId = parent.id;
4078
- parentIdRef.current = parentId;
4079
- let cancelled = false;
4080
- const init = async () => {
4081
- try {
4082
- const att = await ctx.session.createAttachmentEntity({
4083
- parentEntityId: parentId,
4084
- position: position ?? [0, 0, 0],
4085
- size,
4086
- ownerViewId: ctx.reality.id
4087
- });
4088
- if (cancelled) {
4089
- att.destroy();
4090
- return;
4091
- }
4092
- const windowProxy = att.getWindowProxy();
4093
- setOpenWindowStyle(windowProxy);
4094
- windowProxy.document.body.style.display = "block";
4095
- windowProxy.document.body.style.minWidth = "100%";
4096
- windowProxy.document.body.style.maxWidth = "100%";
4097
- windowProxy.document.body.style.minHeight = "100%";
4098
- const viewport = windowProxy.document.querySelector(
4099
- 'meta[name="viewport"]'
4100
- );
4101
- if (!viewport) {
4102
- const meta = windowProxy.document.createElement("meta");
4103
- meta.name = "viewport";
4104
- meta.content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no";
4105
- windowProxy.document.head.appendChild(meta);
4106
- }
4107
- const base = windowProxy.document.createElement("base");
4108
- base.href = document.baseURI;
4109
- windowProxy.document.head.appendChild(base);
4110
- attachmentRef.current = att;
4111
- setChildWindow(windowProxy);
4112
- ctx.attachmentRegistry.addContainer(
4113
- attachmentNameRef.current,
4114
- instanceIdRef.current,
4115
- att.getContainer()
4116
- );
4117
- } catch (error) {
4118
- console.error("[AttachmentEntity] init error:", error);
4119
- }
4120
- };
4121
- init();
4122
- return () => {
4123
- cancelled = true;
4124
- const att = attachmentRef.current;
4125
- if (att) {
4126
- ctx.attachmentRegistry.removeContainer(
4127
- attachmentNameRef.current,
4128
- instanceIdRef.current
4129
- );
4130
- att.destroy();
4131
- attachmentRef.current = null;
4132
- setChildWindow(null);
4133
- }
4134
- };
4135
- }, [ctx, parent]);
4136
- useEffect28(() => {
4137
- if (!ctx) return;
4138
- const att = attachmentRef.current;
4139
- const prevName = attachmentNameRef.current;
4140
- if (att && prevName !== attachmentName) {
4141
- ctx.attachmentRegistry.removeContainer(prevName, instanceIdRef.current);
4142
- ctx.attachmentRegistry.addContainer(
4143
- attachmentName,
4144
- instanceIdRef.current,
4145
- att.getContainer()
4146
- );
4147
- attachmentNameRef.current = attachmentName;
4148
- } else {
4149
- attachmentNameRef.current = attachmentName;
4150
- }
4151
- }, [ctx, attachmentName]);
4152
- useSyncHeadStyles(childWindow);
4153
- useEffect28(() => {
4154
- if (!attachmentRef.current) return;
4155
- attachmentRef.current.update({ position, size });
4156
- }, [position?.[0], position?.[1], position?.[2], size?.width, size?.height]);
4157
- return null;
4158
- };
4159
-
4160
- // src/reality/components/Material.tsx
4161
- import { jsx as jsx24 } from "react/jsx-runtime";
4162
- var Material = (props) => {
4163
- if (props.type === "unlit") {
4164
- const { type, ...rest } = props;
4165
- return /* @__PURE__ */ jsx24(UnlitMaterial, { ...rest });
4166
- }
4167
- return null;
4168
- };
4169
-
4170
- // src/Model.tsx
4171
- import { forwardRef as forwardRef20 } from "react";
4172
- import { jsx as jsx25 } from "react/jsx-runtime";
4173
- var spatial2 = new Spatial();
4174
- function ModelBase(props, ref) {
4175
- const insideAttachment = useInsideAttachment();
4176
- const { "enable-xr": enableXR, ...restProps } = props;
4177
- if (!enableXR || !spatial2.runInSpatialWeb() || insideAttachment) {
4178
- const {
4179
- onSpatialTap,
4180
- onSpatialDragStart,
4181
- onSpatialDrag,
4182
- onSpatialDragEnd,
4183
- onSpatialRotate,
4184
- onSpatialRotateEnd,
4185
- onSpatialMagnify,
4186
- onSpatialMagnifyEnd,
4187
- spatialEventOptions: _spatialEventOptions,
4188
- ...modelProps
4189
- } = restProps;
4190
- return /* @__PURE__ */ jsx25("model", { ref, ...modelProps });
4191
- }
4192
- return /* @__PURE__ */ jsx25(SpatializedStatic3DElementContainer, { ref, ...restProps });
4193
- }
4194
- var Model = withSSRSupported(forwardRef20(ModelBase));
4195
- Model.displayName = "Model";
4196
-
4197
- // src/useMetrics.tsx
4198
- import { useSyncExternalStore } from "react";
4199
- function useMetrics() {
4200
- useSyncExternalStore(PhysicalMetrics.subscribe, PhysicalMetrics.getValue);
4201
- const { pointToPhysical, physicalToPoint } = PhysicalMetrics;
4202
- return { pointToPhysical, physicalToPoint };
4203
- }
4204
-
4205
- // src/jsx/jsx-shared.ts
4206
- import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
4207
- import reactJSXRuntime from "react/jsx-runtime";
4208
- import { createElement as reactCreateElement } from "react";
4209
- var attributeFlag = "enable-xr";
4210
- var styleFlag = "enableXr";
4211
- var classFlag = "__enableXr__";
4212
- var xrMonitorFlag = "enable-xr-monitor";
4213
- function replaceToSpatialPrimitiveType(type, props) {
4214
- if (type === Model || type === Reality) {
4215
- return type;
4216
- }
4217
- const propsObject = props;
4218
- if (attributeFlag in propsObject) {
4219
- delete propsObject[attributeFlag];
4220
- return withSpatialized2DElementContainer(type);
4221
- }
4222
- if (xrMonitorFlag in propsObject) {
4223
- delete propsObject[xrMonitorFlag];
4224
- return withSpatialMonitor(type);
4225
- }
4226
- if (propsObject && propsObject.style && styleFlag in propsObject.style) {
4227
- delete propsObject.style[styleFlag];
4228
- return withSpatialized2DElementContainer(type);
4229
- }
4230
- if (propsObject && typeof propsObject.className === "string") {
4231
- const originalClassNames = propsObject.className.split(" ");
4232
- const idx = originalClassNames.indexOf(classFlag);
4233
- if (idx !== -1) {
4234
- originalClassNames.splice(idx, 1);
4235
- propsObject.className = originalClassNames.join(" ");
4236
- return withSpatialized2DElementContainer(type);
4237
- }
4238
- }
4239
- return type;
4240
- }
4241
- function createElement(...args) {
4242
- const [type, props, ...rest] = args;
4243
- const newType = replaceToSpatialPrimitiveType(type, props);
4244
- return reactCreateElement(newType, props, ...rest);
4245
- }
4246
-
4247
- // src/utils/convertCoordinate.ts
4248
- function resolveSpatialObjectId(target) {
4249
- if (typeof window !== "undefined" && target === window) {
4250
- const scene = getSession()?.getSpatialScene();
4251
- return scene?.id ?? "";
4252
- }
4253
- const maybeEntity = target;
4254
- if (maybeEntity && typeof maybeEntity === "object" && "entity" in maybeEntity) {
4255
- return maybeEntity.entity?.id ?? null;
4256
- }
4257
- const dom = target;
4258
- if (dom && typeof dom === "object") {
4259
- const spatializedElement = dom.__spatializedElement ?? dom.__innerSpatializedElement?.();
4260
- if (spatializedElement && spatializedElement.id) {
4261
- return spatializedElement.id;
4262
- }
4263
- }
4264
- return null;
4265
- }
4266
- async function convertCoordinate(position, { from, to }) {
4267
- try {
4268
- const fromId = resolveSpatialObjectId(from);
4269
- const toId = resolveSpatialObjectId(to);
4270
- if (fromId === null || toId === null) {
4271
- console.warn(
4272
- "convertCoordinate error: from or to is not a valid coordinate convertible"
4273
- );
4274
- return position;
4275
- }
4276
- const spatialScene = getSession()?.getSpatialScene();
4277
- if (!spatialScene) return position;
4278
- const ret = await spatialScene.convertCoordinate(position, fromId, toId);
4279
- return ret ?? position;
4280
- } catch (error) {
4281
- console.warn("convertCoordinate error:", error);
4282
- return position;
4283
- }
4284
- }
4285
-
4286
- // src/index.ts
4287
- var version = "1.7.0";
4288
- if (typeof window !== "undefined") {
4289
- initPolyfill();
4290
- }
4291
- export {
4292
- AttachmentAsset,
4293
- AttachmentEntity,
4294
- BoxEntity as Box,
4295
- BoxEntity,
4296
- ConeEntity as Cone,
4297
- ConeEntity,
4298
- CylinderEntity as Cylinder,
4299
- CylinderEntity,
4300
- Entity,
4301
- Material,
4302
- Model,
4303
- ModelAsset,
4304
- ModelEntity,
4305
- PlaneEntity as Plane,
4306
- PlaneEntity,
4307
- Reality,
4308
- SSRProvider,
4309
- SceneGraph,
4310
- SpatialMonitor,
4311
- Spatialized2DElementContainer,
4312
- SpatializedContainer,
4313
- SpatializedStatic3DElementContainer,
4314
- SphereEntity as Sphere,
4315
- SphereEntity,
4316
- Texture,
4317
- UnlitMaterial,
4318
- WebSpatialRuntime,
4319
- WebSpatialRuntimeError,
4320
- SceneGraph as World,
4321
- convertCoordinate,
4322
- createElement,
4323
- enableDebugTool,
4324
- eventMap,
4325
- getAbsoluteUrl,
4326
- initPolyfill,
4327
- initScene,
4328
- useMetrics,
4329
- version,
4330
- withSpatialMonitor,
4331
- withSpatialized2DElementContainer
4332
- };
4333
- //# sourceMappingURL=index.js.map