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