-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathSelection.tsx
More file actions
53 lines (45 loc) · 1.62 KB
/
Selection.tsx
File metadata and controls
53 lines (45 loc) · 1.62 KB
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
import * as THREE from 'three'
import type React from 'react'
import { createContext, useState, useContext, useEffect, useRef, useMemo } from 'react'
import type { ThreeElements } from '@react-three/fiber'
export type Api = {
selected: THREE.Object3D[]
select: React.Dispatch<React.SetStateAction<THREE.Object3D[]>>
enabled: boolean
}
export type SelectApi = Omit<ThreeElements['group'], 'ref'> & {
enabled?: boolean
}
export const selectionContext = /* @__PURE__ */ createContext<Api>({
select: () => {},
enabled: true,
selected: []
})
export function Selection({ children, enabled = true }: { enabled?: boolean; children: React.ReactNode }) {
const [selected, select] = useState<THREE.Object3D[]>([])
const value = useMemo(() => ({ selected, select, enabled }), [selected, enabled])
return <selectionContext.Provider value={value}>{children}</selectionContext.Provider>
}
export function Select({ enabled = false, children, ...props }: SelectApi) {
const group = useRef<THREE.Group>(new THREE.Group())
const {select = () => {}} = useContext(selectionContext)
useEffect(() => {
if (!enabled || !group.current) return
const current: THREE.Object3D[] = []
group.current.traverse((o) => {
if (o.type === 'Mesh') current.push(o)
})
select((prev) => {
const notIncluded = current.filter(obj => !prev.includes(obj))
return notIncluded.length > 0 ? [...prev, ...notIncluded] : prev
})
return () => {
select((prev) => prev.filter(obj => !current.includes(obj)))
}
}, [enabled, select, children])
return (
<group ref={group} {...props}>
{children}
</group>
)
}