import React , { useState , useRef } from 'react' ; import { ControlsContext } from '../contexts/controls-context' ; import { Canvas as R3FCanvas } from 'react-three-fiber' ; import { ControlItem } from 'types' ; export const ControlsProvider = ( { children , } ) => { const [ controls , setControls ] = useState < ControlItem [ ] > ( [ ] ) ; const values = useRef ( new Map ( ) ) ; const gui = useRef ( new Map ( ) ) ; const state = useRef ( new Map ( ) ) ; const context = { values , gui , state , controls , addControl : ( control ) => { control . id = control . id ?? String ( Math . random ( ) ) ; setControls ( ctrls => { return [ ... ctrls , control ] ; } ) ; return control ; } , removeControl : ( ctrl ) => { setControls ( ctrls => ctrls . filter ( c => c . id !== ctrl . id ) ) ; } , } ; return ( < ControlsContext . Provider value = { context } > { children } < /ControlsContext.Provider>); } ; export function withControls ( CanvasEl ) { return ( { children , ... props } ) => ( < ControlsContext . Consumer > { value => ( < CanvasEl { ... props } > < ControlsContext . Provider value = { value } > { children } < /ControlsContext.Provider> < /CanvasEl>)} < /ControlsContext.Consumer>); } export const Canvas = withControls ( R3FCanvas ) ;