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)
|
|
|
|
|
2021-09-05 23:33:17 +02:00
|
|
|
const useWrapperContext = (): {sheet: ISheet | undefined} => {
|
|
|
|
const val = useContext(ctx)
|
|
|
|
if (!val) {
|
|
|
|
throw new Error(
|
|
|
|
`No sheet found. You need to add a <SheetProvider> higher up in the tree. https://docs.theatrejs.com/r3f.html#sheetprovider`,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
return val
|
2021-09-05 23:21:18 +02:00
|
|
|
}
|
|
|
|
|
2021-09-05 23:33:17 +02:00
|
|
|
export const useCurrentSheet = (): ISheet | undefined => {
|
|
|
|
return useWrapperContext().sheet
|
|
|
|
}
|
|
|
|
|
|
|
|
const SheetProvider: React.FC<{
|
2021-07-31 15:10:08 +02:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2021-09-05 23:33:17 +02:00
|
|
|
export default SheetProvider
|