UNPKG

motion-wave

Version:

A library suitable for generating animated waveforms.

56 lines (55 loc) 1.68 kB
import * as React from 'react'; import { createWave } from './createWave'; export const useLayoutEffect = typeof window !== 'undefined' && window.document ? React.useLayoutEffect : // eslint-disable-next-line @typescript-eslint/no-empty-function () => { }; export const useWave = (config, ref) => { const { frequency, amplitude, phase, speed, offset, color } = config; const canvasRef = React.useRef(null); const handler = React.useRef(null); useLayoutEffect(() => { if (!handler.current) { handler.current = createWave(canvasRef.current, { frequency, amplitude, phase, speed, offset, color, }); handler.current.start(); } else { handler.current.setConfig({ frequency, amplitude, phase, speed, offset, color, }); } }, [amplitude, color, frequency, offset, phase, speed]); useLayoutEffect(() => { if (typeof ref === 'function') { ref(handler.current); return () => { ref(null); }; } else if (typeof ref === 'object' && ref !== null && 'current' in ref) { ref.current = handler.current; return () => { ref.current = null; }; } }, []); useLayoutEffect(() => { return () => { handler.current?.stop(); handler.current = null; }; }, []); return [canvasRef, handler]; };