-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathrenderer.test.tsx
1018 lines (823 loc) Β· 29.2 KB
/
renderer.test.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as React from 'react'
import * as THREE from 'three'
import { createCanvas } from '@react-three/test-renderer/src/createTestCanvas'
import {
ReconcilerRoot,
createRoot,
act,
useFrame,
extend,
ReactThreeFiber,
useThree,
createPortal,
} from '../../src/index'
import { UseBoundStore } from 'zustand'
import { privateKeys, RootState } from '../../src/core/store'
import { Instance } from '../../src/core/renderer'
type ComponentMesh = THREE.Mesh<THREE.BoxBufferGeometry, THREE.MeshBasicMaterial>
interface ObjectWithBackground extends THREE.Object3D {
background: THREE.Color
}
/* This class is used for one of the tests */
class HasObject3dMember extends THREE.Object3D {
public attachment?: THREE.Object3D = undefined
}
/* This class is used for one of the tests */
class HasObject3dMethods extends THREE.Object3D {
attachedObj3d?: THREE.Object3D
detachedObj3d?: THREE.Object3D
customAttach(obj3d: THREE.Object3D) {
this.attachedObj3d = obj3d
}
detach(obj3d: THREE.Object3D) {
this.detachedObj3d = obj3d
}
}
class MyColor extends THREE.Color {
constructor(col: number) {
super(col)
}
}
extend({ HasObject3dMember, HasObject3dMethods })
declare module '@react-three/fiber' {
interface ThreeElements {
hasObject3dMember: ReactThreeFiber.Node<HasObject3dMember, typeof HasObject3dMember>
hasObject3dMethods: ReactThreeFiber.Node<HasObject3dMethods, typeof HasObject3dMethods>
myColor: ReactThreeFiber.Node<MyColor, typeof MyColor>
}
}
beforeAll(() => {
Object.defineProperty(window, 'devicePixelRatio', {
configurable: true,
value: 2,
})
})
describe('renderer', () => {
let root: ReconcilerRoot<HTMLCanvasElement> = null!
beforeEach(() => {
const canvas = createCanvas()
root = createRoot(canvas)
})
afterEach(() => {
root.unmount()
})
it('renders a simple component', async () => {
const Mesh = () => {
return (
<mesh>
<boxGeometry args={[2, 2]} />
<meshBasicMaterial />
</mesh>
)
}
let scene: THREE.Scene = null!
await act(async () => {
scene = root.render(<Mesh />).getState().scene
})
expect(scene.children[0].type).toEqual('Mesh')
expect((scene.children[0] as ComponentMesh).geometry.type).toEqual('BoxGeometry')
expect((scene.children[0] as ComponentMesh).material.type).toEqual('MeshBasicMaterial')
expect((scene.children[0] as THREE.Mesh<THREE.BoxGeometry, THREE.MeshStandardMaterial>).material.type).toEqual(
'MeshBasicMaterial',
)
})
it('renders an empty scene', async () => {
const Empty = () => null
let scene: THREE.Scene = null!
await act(async () => {
scene = root.render(<Empty />).getState().scene
})
expect(scene.type).toEqual('Scene')
expect(scene.children).toEqual([])
})
it('can render a composite component', async () => {
class Parent extends React.Component {
render() {
return (
<group>
<color attach="background" args={[0, 0, 0]} />
<Child />
</group>
)
}
}
const Child = () => {
return (
<mesh>
<boxGeometry args={[2, 2]} />
<meshBasicMaterial />
</mesh>
)
}
let scene: THREE.Scene = null!
await act(async () => {
scene = root.render(<Parent />).getState().scene
})
expect(scene.children[0].type).toEqual('Group')
expect((scene.children[0] as ObjectWithBackground).background.getStyle()).toEqual('rgb(0,0,0)')
expect(scene.children[0].children[0].type).toEqual('Mesh')
expect((scene.children[0].children[0] as ComponentMesh).geometry.type).toEqual('BoxGeometry')
expect((scene.children[0].children[0] as ComponentMesh).material.type).toEqual('MeshBasicMaterial')
expect(
(scene.children[0].children[0] as THREE.Mesh<THREE.BoxGeometry, THREE.MeshStandardMaterial>).material.type,
).toEqual('MeshBasicMaterial')
})
it('renders some basics with an update', async () => {
let renders = 0
class Component extends React.PureComponent {
state = { pos: 3 }
componentDidMount() {
this.setState({ pos: 7 })
}
render() {
renders++
return (
<group position-x={this.state.pos}>
<Child />
<Null />
</group>
)
}
}
const Child = () => {
renders++
return <color attach="background" args={[0, 0, 0]} />
}
const Null = () => {
renders++
return null
}
let scene: THREE.Scene = null!
await act(async () => {
scene = root.render(<Component />).getState().scene
})
expect(scene.children[0].position.x).toEqual(7)
expect(renders).toBe(6)
})
it('updates types & names', async () => {
let scene: THREE.Scene = null!
await act(async () => {
scene = root
.render(
<mesh>
<meshBasicMaterial name="basicMat">
<color attach="color" args={[0, 0, 0]} />
</meshBasicMaterial>
</mesh>,
)
.getState().scene
})
expect((scene.children[0] as THREE.Mesh<THREE.BoxGeometry, THREE.MeshBasicMaterial>).material.type).toEqual(
'MeshBasicMaterial',
)
expect((scene.children[0] as THREE.Mesh<THREE.BoxGeometry, THREE.MeshBasicMaterial>).material.name).toEqual(
'basicMat',
)
await act(async () => {
scene = root
.render(
<mesh>
<meshStandardMaterial name="standardMat">
<color attach="color" args={[255, 255, 255]} />
</meshStandardMaterial>
</mesh>,
)
.getState().scene
})
expect((scene.children[0] as THREE.Mesh<THREE.BoxGeometry, THREE.MeshStandardMaterial>).material.type).toEqual(
'MeshStandardMaterial',
)
expect((scene.children[0] as THREE.Mesh<THREE.BoxGeometry, THREE.MeshStandardMaterial>).material.name).toEqual(
'standardMat',
)
})
it('should forward ref three object', async () => {
// Note: Passing directly should be less strict, and assigning current should be more strict
let immutableRef!: React.RefObject<THREE.Mesh>
let mutableRef!: React.MutableRefObject<THREE.Mesh | null>
let mutableRefSpecific!: React.MutableRefObject<THREE.Mesh | null>
const RefTest = () => {
immutableRef = React.createRef()
mutableRef = React.useRef(null)
mutableRefSpecific = React.useRef(null)
return (
<>
<mesh ref={immutableRef} />
<mesh ref={mutableRef} />
<mesh ref={(r) => (mutableRefSpecific.current = r)} />
</>
)
}
await act(async () => {
root.render(<RefTest />)
})
expect(immutableRef.current).toBeTruthy()
expect(mutableRef.current).toBeTruthy()
expect(mutableRefSpecific.current).toBeTruthy()
})
it('attaches Object3D children that use attach', async () => {
let scene: THREE.Scene = null!
await act(async () => {
scene = root
.render(
<hasObject3dMember>
<mesh attach="attachment" />
</hasObject3dMember>,
)
.getState().scene
})
const attachedMesh = (scene.children[0] as HasObject3dMember).attachment
expect(attachedMesh).toBeDefined()
expect(attachedMesh?.type).toBe('Mesh')
// attaching is *instead of* being a regular child
expect(scene.children[0].children.length).toBe(0)
})
it('can attach a Scene', async () => {
let scene: THREE.Scene = null!
await act(async () => {
scene = root
.render(
<hasObject3dMember>
<scene attach="attachment" />
</hasObject3dMember>,
)
.getState().scene
})
const attachedScene = (scene.children[0] as HasObject3dMember).attachment
expect(attachedScene).toBeDefined()
expect(attachedScene?.type).toBe('Scene')
// attaching is *instead of* being a regular child
expect(scene.children[0].children.length).toBe(0)
})
describe('attaches Object3D children that use attachFns', () => {
it('attachFns with cleanup', async () => {
let scene: THREE.Scene = null!
await act(async () => {
scene = root
.render(
<hasObject3dMethods>
<mesh attach={(parent, self) => (parent.customAttach(self), () => parent.detach(self))} />
</hasObject3dMethods>,
)
.getState().scene
})
const attachedMesh = (scene.children[0] as HasObject3dMethods).attachedObj3d
expect(attachedMesh).toBeDefined()
expect(attachedMesh?.type).toBe('Mesh')
// attaching is *instead of* being a regular child
expect(scene.children[0].children.length).toBe(0)
// and now detach ..
expect((scene.children[0] as HasObject3dMethods).detachedObj3d).toBeUndefined()
await act(async () => {
root.render(<hasObject3dMethods />)
})
const detachedMesh = (scene.children[0] as HasObject3dMethods).detachedObj3d
expect(detachedMesh).toBe(attachedMesh)
})
it('attachFns as functions', async () => {
let scene: THREE.Scene = null!
let attachedMesh: Instance = null!
let detachedMesh: Instance = null!
await act(async () => {
scene = root
.render(
<hasObject3dMethods>
<mesh attach={(parent) => ((attachedMesh = parent), () => (detachedMesh = parent))} />
</hasObject3dMethods>,
)
.getState().scene
})
expect(attachedMesh).toBeDefined()
expect(attachedMesh?.type).toBe('Object3D')
// attaching is *instead of* being a regular child
expect(scene.children[0].children.length).toBe(0)
await act(async () => {
root.render(<hasObject3dMethods />)
})
expect(detachedMesh).toBe(attachedMesh)
})
})
it('does the full lifecycle', async () => {
const log: string[] = []
class Log extends React.Component<{ name: string }> {
render() {
log.push('render ' + this.props.name)
return <group />
}
componentDidMount() {
log.push('mount ' + this.props.name)
}
componentWillUnmount() {
log.push('unmount ' + this.props.name)
}
}
await act(async () => {
root.render(<Log key="foo" name="Foo" />)
})
await act(async () => {
root.unmount()
})
expect(log).toEqual(['render Foo', 'mount Foo', 'unmount Foo'])
})
it('will mount/unmount event handlers correctly', async () => {
let state: RootState = null!
let mounted = false
let attachEvents = false
const EventfulComponent = () => (mounted ? <group onClick={attachEvents ? () => void 0 : undefined} /> : null)
// Test initial mount without events
mounted = true
await act(async () => {
state = root.render(<EventfulComponent />).getState()
})
expect(state.internal.interaction.length).toBe(0)
// Test initial mount with events
attachEvents = true
await act(async () => {
state = root.render(<EventfulComponent />).getState()
})
expect(state.internal.interaction.length).not.toBe(0)
// Test events update
attachEvents = false
await act(async () => {
state = root.render(<EventfulComponent />).getState()
})
expect(state.internal.interaction.length).toBe(0)
attachEvents = true
await act(async () => {
state = root.render(<EventfulComponent />).getState()
})
expect(state.internal.interaction.length).not.toBe(0)
// Test unmount with events
mounted = false
await act(async () => {
state = root.render(<EventfulComponent />).getState()
})
expect(state.internal.interaction.length).toBe(0)
})
it('will create an identical instance when reconstructing', async () => {
let state: RootState = null!
const instances: { uuid: string; parentUUID?: string; childUUID?: string }[] = []
const object1 = new THREE.Group()
const object2 = new THREE.Group()
const Test = ({ first }: { first?: boolean }) => (
<primitive object={first ? object1 : object2} onPointerOver={() => null}>
<group />
</primitive>
)
await act(async () => {
state = root.render(<Test first />).getState()
})
instances.push({
uuid: state.scene.children[0].uuid,
parentUUID: state.scene.children[0].parent?.uuid,
childUUID: state.scene.children[0].children[0]?.uuid,
})
expect(state.scene.children[0]).toBe(object1)
await act(async () => {
state = root.render(<Test />).getState()
})
instances.push({
uuid: state.scene.children[0].uuid,
parentUUID: state.scene.children[0].parent?.uuid,
childUUID: state.scene.children[0].children[0]?.uuid,
})
const [oldInstance, newInstance] = instances
// Swapped to new instance
expect(state.scene.children[0]).toBe(object2)
// Preserves scene hierarchy
expect(oldInstance.parentUUID).toBe(newInstance.parentUUID)
expect(oldInstance.childUUID).toBe(newInstance.childUUID)
// Rebinds events
expect(state.internal.interaction.length).not.toBe(0)
})
it('can swap primitives', async () => {
let state: RootState = null!
const o1 = new THREE.Group()
o1.add(new THREE.Group())
const o2 = new THREE.Group()
const Test = ({ n }: { n: number }) => (
<primitive object={n === 1 ? o1 : o2}>
<group attach="test" />
</primitive>
)
await act(async () => {
state = root.render(<Test n={1} />).getState()
})
// Initial object is added with children and attachments
expect(state.scene.children[0]).toBe(o1)
expect(state.scene.children[0].children.length).toBe(1)
expect((state.scene.children[0] as any).test).toBeInstanceOf(THREE.Group)
await act(async () => {
state = root.render(<Test n={2} />).getState()
})
// Swapped to object 2, does not copy old children, copies attachments
expect(state.scene.children[0]).toBe(o2)
expect(state.scene.children[0].children.length).toBe(0)
expect((state.scene.children[0] as any).test).toBeInstanceOf(THREE.Group)
})
it('can swap 4 array primitives', async () => {
let state: RootState = null!
const a = new THREE.Group()
const b = new THREE.Group()
const c = new THREE.Group()
const d = new THREE.Group()
const array = [a, b, c, d]
const Test = ({ array }: { array: THREE.Group[] }) => (
<>
{array.map((group, i) => (
<primitive key={i} object={group} />
))}
</>
)
await act(async () => {
state = root.render(<Test array={array} />).getState()
})
expect(state.scene.children[0]).toBe(a)
expect(state.scene.children[1]).toBe(b)
expect(state.scene.children[2]).toBe(c)
expect(state.scene.children[3]).toBe(d)
const reversedArray = [...array.reverse()]
await act(async () => {
state = root.render(<Test array={reversedArray} />).getState()
})
expect(state.scene.children[0]).toBe(d)
expect(state.scene.children[1]).toBe(c)
expect(state.scene.children[2]).toBe(b)
expect(state.scene.children[3]).toBe(a)
const mixedArray = [b, a, d, c]
await act(async () => {
state = root.render(<Test array={mixedArray} />).getState()
})
expect(state.scene.children[0]).toBe(b)
expect(state.scene.children[1]).toBe(a)
expect(state.scene.children[2]).toBe(d)
expect(state.scene.children[3]).toBe(c)
})
it('will make an Orthographic Camera & set the position', async () => {
let camera: THREE.Camera = null!
await act(async () => {
camera = root
.configure({ orthographic: true, camera: { position: [0, 0, 5] } })
.render(<group />)
.getState().camera
})
expect(camera.type).toEqual('OrthographicCamera')
expect(camera.position.z).toEqual(5)
})
it('should handle an performance changing functions', async () => {
let state: UseBoundStore<RootState> = null!
await act(async () => {
state = root.configure({ dpr: [1, 2], performance: { min: 0.2 } }).render(<group />)
})
expect(state.getState().viewport.initialDpr).toEqual(2)
expect(state.getState().performance.min).toEqual(0.2)
expect(state.getState().performance.current).toEqual(1)
await act(async () => {
state.getState().setDpr(0.1)
})
expect(state.getState().viewport.dpr).toEqual(0.1)
jest.useFakeTimers()
await act(async () => {
state.getState().performance.regress()
jest.advanceTimersByTime(100)
})
expect(state.getState().performance.current).toEqual(0.2)
await act(async () => {
jest.advanceTimersByTime(200)
})
expect(state.getState().performance.current).toEqual(1)
jest.useRealTimers()
})
it('should set PCFSoftShadowMap as the default shadow map', async () => {
let state: UseBoundStore<RootState> = null!
await act(async () => {
state = root.configure({ shadows: true }).render(<group />)
})
expect(state.getState().gl.shadowMap.type).toBe(THREE.PCFSoftShadowMap)
})
it('should set tonemapping to ACESFilmicToneMapping and outputEncoding to sRGBEncoding if linear is false', async () => {
let state: UseBoundStore<RootState> = null!
await act(async () => {
state = root.configure({ linear: false }).render(<group />)
})
expect(state.getState().gl.toneMapping).toBe(THREE.ACESFilmicToneMapping)
expect(state.getState().gl.outputEncoding).toBe(THREE.sRGBEncoding)
})
it('should toggle render mode in xr', async () => {
let state: RootState = null!
await act(async () => {
state = root.render(<group />).getState()
state.gl.xr.isPresenting = true
state.gl.xr.dispatchEvent({ type: 'sessionstart' })
})
expect(state.gl.xr.enabled).toEqual(true)
await act(async () => {
state.gl.xr.isPresenting = false
state.gl.xr.dispatchEvent({ type: 'sessionend' })
})
expect(state.gl.xr.enabled).toEqual(false)
})
it('should respect frameloop="never" in xr', async () => {
let respected = true
await act(async () => {
const TestGroup = () => {
useFrame(() => (respected = false))
return <group />
}
const state = root
.configure({ frameloop: 'never' })
.render(<TestGroup />)
.getState()
state.gl.xr.isPresenting = true
state.gl.xr.dispatchEvent({ type: 'sessionstart' })
})
expect(respected).toEqual(true)
})
it('will render components that are extended', async () => {
const testExtend = async () => {
await act(async () => {
extend({ MyColor })
root.render(<myColor args={[0x0000ff]} />)
})
}
expect(() => testExtend()).not.toThrow()
})
it('should set renderer props via gl prop', async () => {
let gl: THREE.WebGLRenderer = null!
await act(async () => {
gl = root
.configure({ gl: { physicallyCorrectLights: true } })
.render(<group />)
.getState().gl
})
expect(gl.physicallyCorrectLights).toBe(true)
})
it('should update scene via scene prop', async () => {
let scene: THREE.Scene = null!
await act(async () => {
scene = root
.configure({ scene: { name: 'test' } })
.render(<group />)
.getState().scene
})
expect(scene.name).toBe('test')
})
it('should set a custom scene via scene prop', async () => {
let scene: THREE.Scene = null!
const prop = new THREE.Scene()
await act(async () => {
scene = root
.configure({ scene: prop })
.render(<group />)
.getState().scene
})
expect(prop).toBe(scene)
})
it('should set a renderer via gl callback', async () => {
class Renderer extends THREE.WebGLRenderer {}
let gl: Renderer = null!
await act(async () => {
gl = root
.configure({ gl: (canvas) => new Renderer({ canvas }) })
.render(<group />)
.getState().gl
})
expect(gl instanceof Renderer).toBe(true)
})
it('should respect color management preferences via gl', async () => {
const texture = new THREE.Texture() as THREE.Texture & { colorSpace?: string }
let key = 0
function Test() {
return <meshBasicMaterial key={key++} map={texture} />
}
const LinearEncoding = 3000
const sRGBEncoding = 3001
let gl: THREE.WebGLRenderer & { outputColorSpace?: string } = null!
await act(async () => (gl = root.render(<Test />).getState().gl))
expect(gl.outputEncoding).toBe(sRGBEncoding)
expect(gl.toneMapping).toBe(THREE.ACESFilmicToneMapping)
expect(texture.encoding).toBe(sRGBEncoding)
await act(async () => root.configure({ linear: true, flat: true }).render(<Test />))
expect(gl.outputEncoding).toBe(LinearEncoding)
expect(gl.toneMapping).toBe(THREE.NoToneMapping)
expect(texture.encoding).toBe(LinearEncoding)
// Sets outputColorSpace since r152
const SRGBColorSpace = 'srgb'
const LinearSRGBColorSpace = 'srgb-linear'
gl.outputColorSpace ??= ''
texture.colorSpace ??= ''
await act(async () => root.configure({ linear: true }).render(<Test />))
expect(gl.outputColorSpace).toBe(LinearSRGBColorSpace)
expect(texture.colorSpace).toBe(LinearSRGBColorSpace)
await act(async () => root.configure({ linear: false }).render(<Test />))
expect(gl.outputColorSpace).toBe(SRGBColorSpace)
expect(texture.colorSpace).toBe(SRGBColorSpace)
})
it('should respect legacy prop', async () => {
// <= r138 internal fallback
const material = React.createRef<THREE.MeshBasicMaterial>()
extend({ ColorManagement: null })
await act(async () => root.render(<meshBasicMaterial ref={material} color="#111111" />))
expect((THREE as any).ColorManagement.legacyMode).toBe(false)
expect(material.current!.color.toArray()).toStrictEqual(new THREE.Color('#111111').convertSRGBToLinear().toArray())
extend({ ColorManagement: (THREE as any).ColorManagement })
// r139 legacyMode
await act(async () => {
root.configure({ legacy: true }).render(<group />)
})
expect((THREE as any).ColorManagement.legacyMode).toBe(true)
await act(async () => {
root.configure({ legacy: false }).render(<group />)
})
expect((THREE as any).ColorManagement.legacyMode).toBe(false)
// r150 !enabled
;(THREE as any).ColorManagement.enabled = true
await act(async () => {
root.configure({ legacy: true }).render(<group />)
})
expect((THREE as any).ColorManagement.enabled).toBe(false)
await act(async () => {
root.configure({ legacy: false }).render(<group />)
})
expect((THREE as any).ColorManagement.enabled).toBe(true)
})
it('can handle createPortal', async () => {
const scene = new THREE.Scene()
let state: RootState = null!
let portalState: RootState = null!
const Normal = () => {
const three = useThree()
state = three
return <group />
}
const Portal = () => {
const three = useThree()
portalState = three
return <group />
}
await act(async () => {
root.render(
<>
<Normal />
{createPortal(<Portal />, scene, { scene })}
</>,
)
})
// Renders into portal target
expect(scene.children.length).not.toBe(0)
// Creates an isolated state enclave
expect(state.scene).not.toBe(scene)
expect(portalState.scene).toBe(scene)
// Preserves internal keys
const overwrittenKeys = ['get', 'set', 'events', 'size', 'viewport']
const respectedKeys = privateKeys.filter((key) => overwrittenKeys.includes(key) || state[key] === portalState[key])
expect(respectedKeys).toStrictEqual(privateKeys)
})
it('can handle createPortal on unmounted container', async () => {
let groupHandle!: THREE.Group | null
function Test(props: any) {
const [group, setGroup] = React.useState(null)
groupHandle = group
return (
<group {...props} ref={setGroup}>
{group && createPortal(<mesh />, group)}
</group>
)
}
await act(async () => root.render(<Test key={0} />))
expect(groupHandle).toBeDefined()
const prevUUID = groupHandle!.uuid
await act(async () => root.render(<Test key={1} />))
expect(groupHandle).toBeDefined()
expect(prevUUID).not.toBe(groupHandle!.uuid)
})
it('invalidates pierced props when root is changed', async () => {
const material = React.createRef<THREE.MeshBasicMaterial>()
const texture1 = { needsUpdate: false, name: '' } as THREE.Texture
const texture2 = { needsUpdate: false, name: '' } as THREE.Texture
await act(async () =>
root.render(<meshBasicMaterial ref={material} map={texture1} map-needsUpdate={true} map-name="test" />),
)
expect(material.current!.map).toBe(texture1)
expect(texture1.needsUpdate).toBe(true)
expect(texture1.name).toBe('test')
await act(async () =>
root.render(<meshBasicMaterial ref={material} map={texture2} map-needsUpdate={true} map-name="test" />),
)
expect(material.current!.map).toBe(texture2)
expect(texture2.needsUpdate).toBe(true)
expect(texture2.name).toBe('test')
})
// https://github.com/mrdoob/three.js/issues/21209
it("can handle HMR default where three.js isn't reliable", async () => {
const ref = React.createRef<THREE.Mesh>()
function Test() {
const [scale, setScale] = React.useState(true)
const props: any = {}
if (scale) props.scale = 0.5
React.useEffect(() => void setScale(false), [])
return <mesh ref={ref} {...props} />
}
await act(async () => root.render(<Test />))
expect(ref.current!.scale.toArray()).toStrictEqual(new THREE.Object3D().scale.toArray())
})
it("onUpdate shouldn't update itself", async () => {
const one = jest.fn()
const two = jest.fn()
const Test = (props: Partial<JSX.IntrinsicElements['mesh']>) => <mesh {...props} />
await act(async () => root.render(<Test onUpdate={one} />))
await act(async () => root.render(<Test onUpdate={two} />))
expect(one).toBeCalledTimes(1)
expect(two).toBeCalledTimes(0)
})
it("camera props shouldn't overwrite state", async () => {
const camera = new THREE.OrthographicCamera()
function Test() {
const set = useThree((state) => state.set)
React.useMemo(() => set({ camera }), [set])
return null
}
const store = await act(async () => root.render(<Test />))
expect(store.getState().camera).toBe(camera)
root.configure({ camera: { name: 'test' } })
await act(async () => root.render(<Test />))
expect(store.getState().camera).toBe(camera)
expect(camera.name).not.toBe('test')
})
it('should safely handle updates to the object prop', async () => {
const ref = React.createRef<THREE.Object3D>()
const child = React.createRef<THREE.Object3D>()
const attachedChild = React.createRef<THREE.Object3D>()
const Test = (props: JSX.IntrinsicElements['primitive']) => (
<primitive {...props} ref={ref}>
<object3D ref={child} />
<object3D ref={attachedChild} attach="userData-attach" />
</primitive>
)
const object1 = new THREE.Object3D()
const child1 = new THREE.Object3D()
object1.add(child1)
const object2 = new THREE.Object3D()
const child2 = new THREE.Object3D()
object2.add(child2)
// Initial
await act(async () => root.render(<Test object={object1} />))
expect(ref.current).toBe(object1)
expect(ref.current!.children).toStrictEqual([child1, child.current])
expect(ref.current!.userData.attach).toBe(attachedChild.current)
// Update
await act(async () => root.render(<Test object={object2} />))
expect(ref.current).toBe(object2)
expect(ref.current!.children).toStrictEqual([child2, child.current])
expect(ref.current!.userData.attach).toBe(attachedChild.current)
// Revert
await act(async () => root.render(<Test object={object1} />))
expect(ref.current).toBe(object1)
expect(ref.current!.children).toStrictEqual([child1, child.current])
expect(ref.current!.userData.attach).toBe(attachedChild.current)
})
it('should recursively dispose of declarative children', async () => {
const parentDispose = jest.fn()
const childDispose = jest.fn()
await act(async () =>
root.render(
<mesh dispose={parentDispose}>
<mesh dispose={childDispose} />
</mesh>,
),
)
await act(async () => root.render(null))
expect(parentDispose).toBeCalledTimes(1)
expect(childDispose).toBeCalledTimes(1)
})
it('should not recursively dispose of flagged parent', async () => {
const parentDispose = jest.fn()
const childDispose = jest.fn()
await act(async () =>
root.render(
<group dispose={null}>
<mesh dispose={parentDispose}>
<mesh dispose={childDispose} />
</mesh>
</group>,
),
)
await act(async () => root.render(null))
expect(parentDispose).not.toBeCalled()
expect(childDispose).not.toBeCalled()
})