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