2020-10-21 15:29:25 +03:00
|
|
|
import React, { FunctionComponent, useEffect, useRef } from 'react';
|
2020-10-19 22:25:01 +03:00
|
|
|
import dis from '../../../../dispatcher/dispatcher';
|
|
|
|
import ICanvasEffect from './ICanvasEffect.js';
|
|
|
|
|
|
|
|
type EffectsOverlayProps = {
|
|
|
|
roomWidth: number;
|
|
|
|
}
|
|
|
|
|
2020-10-21 15:29:25 +03:00
|
|
|
const EffectsOverlay: FunctionComponent<EffectsOverlayProps> = ({ roomWidth }) => {
|
2020-10-19 22:25:01 +03:00
|
|
|
const canvasRef = useRef<HTMLCanvasElement>(null);
|
|
|
|
const effectsRef = useRef<Map<String, ICanvasEffect>>(new Map<String, ICanvasEffect>());
|
|
|
|
|
|
|
|
const resize = () => {
|
|
|
|
canvasRef.current.height = window.innerHeight;
|
|
|
|
};
|
|
|
|
|
|
|
|
const lazyLoadEffectModule = async (name: string): Promise<ICanvasEffect> => {
|
2020-10-21 15:29:25 +03:00
|
|
|
if (!name) return null;
|
2020-10-19 22:25:01 +03:00
|
|
|
let effect = effectsRef.current[name] ?? null;
|
2020-10-21 15:29:25 +03:00
|
|
|
if (effect === null) {
|
2020-10-19 22:25:01 +03:00
|
|
|
try {
|
|
|
|
var { default: Effect } = await import(`./${name}`);
|
|
|
|
effect = new Effect();
|
|
|
|
effectsRef.current[name] = effect;
|
|
|
|
} catch (err) {
|
|
|
|
console.warn('Unable to load effect module at \'./${name}\'.', err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return effect;
|
|
|
|
}
|
|
|
|
|
|
|
|
const onAction = (payload: { action: string }) => {
|
|
|
|
const actionPrefix = 'effects.';
|
2020-10-21 15:29:25 +03:00
|
|
|
if (payload.action.indexOf(actionPrefix) === 0) {
|
2020-10-19 22:25:01 +03:00
|
|
|
const effect = payload.action.substr(actionPrefix.length);
|
|
|
|
lazyLoadEffectModule(effect).then((module) => module?.start(canvasRef.current));
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// on mount
|
|
|
|
useEffect(() => {
|
|
|
|
const dispatcherRef = dis.register(onAction);
|
|
|
|
const canvas = canvasRef.current;
|
|
|
|
canvas.width = roomWidth;
|
|
|
|
canvas.height = window.innerHeight;
|
|
|
|
window.addEventListener('resize', resize, true);
|
2020-10-21 15:29:25 +03:00
|
|
|
|
|
|
|
return () => {
|
2020-10-19 22:25:01 +03:00
|
|
|
dis.unregister(dispatcherRef);
|
|
|
|
window.removeEventListener('resize', resize);
|
2020-10-21 15:29:25 +03:00
|
|
|
for (const effect in effectsRef.current) {
|
2020-10-19 22:25:01 +03:00
|
|
|
effectsRef.current[effect]?.stop();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
// on roomWidth change
|
|
|
|
useEffect(() => {
|
|
|
|
canvasRef.current.width = roomWidth;
|
|
|
|
}, [roomWidth]);
|
2020-10-21 15:29:25 +03:00
|
|
|
|
2020-10-19 22:25:01 +03:00
|
|
|
return (
|
|
|
|
<canvas
|
|
|
|
ref={canvasRef}
|
|
|
|
style={{
|
|
|
|
display: 'block',
|
|
|
|
zIndex: 999999,
|
|
|
|
pointerEvents: 'none',
|
|
|
|
position: 'fixed',
|
|
|
|
top: 0,
|
|
|
|
right: 0,
|
|
|
|
}}
|
|
|
|
/>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
export default EffectsOverlay;
|