use useEffect for key listeners on camera control panel (#7827)

* use useEffect for key listeners

* dependencies

* useCallbacks
This commit is contained in:
Josh Hawkins 2023-09-21 05:25:57 -05:00 committed by GitHub
parent 111933d3b4
commit a3eccce8f3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,5 +1,5 @@
import { h } from 'preact'; import { h } from 'preact';
import { useState } from 'preact/hooks'; import { useEffect, useCallback, useState } from 'preact/hooks';
import useSWR from 'swr'; import useSWR from 'swr';
import { usePtzCommand } from '../api/ws'; import { usePtzCommand } from '../api/ws';
import ActivityIndicator from './ActivityIndicator'; import ActivityIndicator from './ActivityIndicator';
@ -27,29 +27,25 @@ export default function CameraControlPanel({ camera = '' }) {
setCurrentPreset(''); setCurrentPreset('');
}; };
const onSetMove = async (e, dir) => { const onSetMove = useCallback(async (e, dir) => {
e.stopPropagation(); e.stopPropagation();
sendPtz(`MOVE_${dir}`); sendPtz(`MOVE_${dir}`);
setCurrentPreset(''); setCurrentPreset('');
}; }, [sendPtz, setCurrentPreset]);
const onSetZoom = async (e, dir) => { const onSetZoom = useCallback(async (e, dir) => {
e.stopPropagation(); e.stopPropagation();
sendPtz(`ZOOM_${dir}`); sendPtz(`ZOOM_${dir}`);
setCurrentPreset(''); setCurrentPreset('');
}; }, [sendPtz, setCurrentPreset]);
const onSetStop = async (e) => { const onSetStop = useCallback(async (e) => {
e.stopPropagation(); e.stopPropagation();
sendPtz('STOP'); sendPtz('STOP');
}; }, [sendPtz]);
if (!ptz) { const keydownListener = useCallback((e) => {
return <ActivityIndicator />; if (!ptz || !e) {
}
document.addEventListener('keydown', (e) => {
if (!e) {
return; return;
} }
@ -83,9 +79,9 @@ export default function CameraControlPanel({ camera = '' }) {
} }
} }
} }
}); }, [onSetMove, onSetZoom, ptz]);
document.addEventListener('keyup', (e) => { const keyupListener = useCallback((e) => {
if (!e || e.repeat) { if (!e || e.repeat) {
return; return;
} }
@ -101,7 +97,20 @@ export default function CameraControlPanel({ camera = '' }) {
e.preventDefault(); e.preventDefault();
onSetStop(e); onSetStop(e);
} }
}); }, [onSetStop]);
useEffect(() => {
document.addEventListener('keydown', keydownListener);
document.addEventListener('keyup', keyupListener);
return () => {
document.removeEventListener('keydown', keydownListener);
document.removeEventListener('keyup', keyupListener);
};
}, [keydownListener, keyupListener, ptz]);
if (!ptz) {
return <ActivityIndicator />;
}
return ( return (
<div data-testid="control-panel" className="p-4 text-center sm:flex justify-start"> <div data-testid="control-panel" className="p-4 text-center sm:flex justify-start">