import React, { useState, useEffect, useRef } from 'react'; import { Props as ChatInputProps } from '../ChatInputs/ChatInputs'; import Microphone from '../icons/Microphone'; import Button from '../ui/Button'; import Tooltip from '../ui/Tooltip'; import cx from 'classnames'; import { useTranslation } from 'react-i18next'; export interface Props { listening?: ChatInputProps['listening']; stopAudio: ChatInputProps['stopAudio']; startListening: ChatInputProps['startListening']; stopListening: ChatInputProps['stopListening']; } const MicrophoneButton = ({ listening, stopAudio, startListening, stopListening, }: Props) => { const { t } = useTranslation(); const [micBtnTooltip, setMicBtnTooltip] = useState(); const intervalRef = useRef(null); const startHold = ( e: | React.TouchEvent | React.MouseEvent ) => { e.preventDefault(); e.stopPropagation(); setMicBtnTooltip(t('write_and_speak.holdToSpeak') || 'Hold to record'); if (intervalRef.current) return; intervalRef.current = setTimeout(() => { stopAudio(); setMicBtnTooltip( t('write_and_speak.releaseToEndListening') || 'Release to end listening' ); startListening(); }, 300); }; const stopHold = (e?: React.MouseEvent | React.TouchEvent) => { if (e) { e.preventDefault(); e.stopPropagation(); } if (intervalRef.current) { clearTimeout(intervalRef.current); intervalRef.current = null; } stopListening(); setMicBtnTooltip(undefined); }; const handleContextMenu = (e: React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); }; const handleTouchStart = (e: React.TouchEvent | React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); startHold(e); }; const handleTouchEnd = (e: React.TouchEvent | React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); stopHold(e); }; useEffect(() => { return () => stopHold(); }, []); return ( {micBtnTooltip || t('write_and_speak.pressAndHoldToSpeak') || 'Press and hold to speak'} } align="topLeft" >
); }; export default MicrophoneButton;