2021-09-05 23:21:18 +02:00
|
|
|
import React, {
|
|
|
|
createContext,
|
|
|
|
useContext,
|
|
|
|
useLayoutEffect,
|
|
|
|
useState,
|
|
|
|
} from 'react'
|
2021-07-31 15:10:08 +02:00
|
|
|
import {useThree} from '@react-three/fiber'
|
|
|
|
import type {ISheet} from '@theatre/core'
|
|
|
|
import {bindToCanvas} from './store'
|
|
|
|
|
2021-09-05 23:21:18 +02:00
|
|
|
const ctx = createContext<{sheet: ISheet | undefined} | undefined>(undefined)
|
|
|
|
|
|
|
|
export const useWrapperContext = ():
|
|
|
|
| {sheet: ISheet | undefined}
|
|
|
|
| undefined => {
|
|
|
|
return useContext(ctx)
|
|
|
|
}
|
|
|
|
|
2021-07-31 15:10:08 +02:00
|
|
|
const Wrapper: React.FC<{
|
|
|
|
getSheet: () => ISheet
|
|
|
|
}> = (props) => {
|
|
|
|
const {scene, gl} = useThree((s) => ({scene: s.scene, gl: s.gl}))
|
2021-09-05 23:21:18 +02:00
|
|
|
const [sheet, setSheet] = useState<ISheet | undefined>(undefined)
|
2021-07-31 15:10:08 +02:00
|
|
|
|
|
|
|
useLayoutEffect(() => {
|
|
|
|
const sheet = props.getSheet()
|
|
|
|
if (!sheet || sheet.type !== 'Theatre_Sheet_PublicAPI') {
|
|
|
|
throw new Error(
|
|
|
|
`getSheet() in <Wrapper getSheet={getSheet}> has returned an invalid value`,
|
|
|
|
)
|
|
|
|
}
|
2021-09-05 23:21:18 +02:00
|
|
|
setSheet(sheet)
|
|
|
|
bindToCanvas({gl, scene})
|
2021-07-31 15:10:08 +02:00
|
|
|
}, [scene, gl])
|
|
|
|
|
2021-09-05 23:21:18 +02:00
|
|
|
return <ctx.Provider value={{sheet}}>{props.children}</ctx.Provider>
|
2021-07-31 15:10:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export default Wrapper
|