-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
39 lines (29 loc) · 1.05 KB
/
index.js
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
import React, { createContext, useContext, useState, useEffect, useRef } from 'react'
import { play, Params } from '@crossaudio/core'
export const context = createContext()
export const useCrossAudio = () => useContext(context)
// I am using React.createElement to avoid JSX compilation
export const CrossAudioProvider = ({ synth, params, ...props }) => {
const [state, setState] = useState(params)
const actualParams = useRef(new Params(params))
useEffect(() => {
play(synth, actualParams.current)
}, [])
const updateState = (value) => {
Object.keys(params).forEach((k) => {
actualParams.current[k] = value[k]
})
setState(value)
}
return React.createElement(context.Provider, { ...props, value: [state, updateState] })
}
export const Canvas = ({ name = 'canvas', ...props }) => {
const ref = useRef()
const [params, setParams] = useCrossAudio()
useEffect(() => {
if (ref.current) {
setParams({ ...params, [name]: ref.current })
}
}, [ref.current])
return React.createElement('canvas', { ...props, ref })
}