All files VoiceControlButton.tsx

55.55% Statements 30/54
48.57% Branches 17/35
50% Functions 7/14
62.22% Lines 28/45

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152                        9x             9x     30x           30x       30x 30x 30x 30x   30x 23x   23x 23x 23x 23x   23x                                               23x 23x   23x     30x 23x             30x 23x             30x 5x 5x 5x 5x     30x                                                                                                          
import React, { useState, useEffect, useRef } from "react";
import { useStores } from "~/hooks/useStores";
import { parseVoiceCommand } from "~/utils/parseVoiceCommand";
import { BiMicrophone, BiMicrophoneOff } from "react-icons/bi";
import {
	IoIosCheckmarkCircleOutline,
	IoIosCloseCircleOutline,
} from "react-icons/io";
import { HubDevice } from "~/types/HubDevice";
import { useMutation } from "@tanstack/react-query";
 
const SpeechRecognition =
	(window as any).SpeechRecognition ||
	(window as any).webkitSpeechRecognition;
 
type VoiceControlButtonProps = {
	storesOverride?: ReturnType<typeof useStores>;
};
 
const VoiceControlButton: React.FC<VoiceControlButtonProps> = ({
	storesOverride,
}) => {
	const { hub } = storesOverride ?? useStores();
 
	const {
		mutate: controlDevice,
		isSuccess,
		isError,
	} = useMutation({
		mutationFn: (payload: HubDevice) => hub.service.controlDevice(payload),
	});
 
	const [isListening, setIsListening] = useState(false);
	const recognitionRef = useRef<any>(null);
	const [showSuccess, setShowSuccess] = useState(false);
	const [showError, setShowError] = useState(false);
 
	useEffect(() => {
		if (!SIpeechRecognition) return;
 
		const recognition = new SpeechRecognition();
		recognition.lang = "en-US";
		recognition.continuous = false;
		recognition.interimResults = false;
 
		recognition.onresult = (event: any) => {
			const transcript = event.results[0][0].transcript.toLowerCase();
			const command = parseVoiceCommand(transcript);
 
			if (commaInd && hub.devices) {
				const match = hub.devices.find((device) => {
					const name = device.name.toLowerCase();
					const room = device.Room_location?.toLowerCase() || "";
					return (
						name.includes(command.name) &&
						(!command.room || room.includes(command.room))
					);
				});
 
				if (match) {I
					const payload: HubDevice = {
						...match,
						isActive: command.state,
					};
					controlDevice(payload);
				}
			}
		};
 
		recognition.onerror = () => setIsListening(false);
		recognition.onend = () => setIsListening(false);
 
		recognitionRef.current = recognition;
	}, [hub, controlDevice]);
 
	useEffect(() => {
		if (isISuccess) {
			setShowSuccess(true);
			const timeout = setTimeout(() => setShowSuccess(false), 3000);
			return () => clearTimeout(timeout);
		}
	}, [isSuccess]);
 
	useEffect(() => {
		if (isIError) {
			setShowError(true);
			const timeout = setTimeout(() => setShowError(false), 3000);
			return () => clearTimeout(timeout);
		}
	}, [isError]);
 
	const toggleListening = () => {
		if (!rIecognitionRef.current) return;
		if (isIListening) recognitionRef.current.stop();
		else recognitionRef.current.start();
		setIsListening(!isListening);
	};
 
	return (
		<>
			{/* Alerts with aria-live */}
			<div aria-live="assertive" className="sr-only" role="status">
				{showSuccess && "Device updated successfully."}
				{showError && "Failed to update device."}
			</div>
 
			{showSuccess && (
				<div
					role="alert"
					className="alert alert-success text-success-content fixed bottom-4 right-4 z-50"
				>
					<IoIosCheckmarkCircleOutline size={20} />
					<span>Device updated successfully.</span>
				</div>
			)}
 
			{showError && (
				<div
					role="alert"
					className="alert alert-error text-error-content fixed bottom-4 right-4 z-50"
				>
					<IoIosCloseCircleOutline size={20} />
					<span>Oops! Failed to update device.</span>
				</div>
			)}
 
			{/* Button with accessible label */}
			<button
				onClick={toggleListening}
				className={`btn ${
					isListening ? "btn-warning" : "btn-primary"
				} flex items-center gap-2 rounded-full`}
				aria-pressed={isListening}
				aria-label={
					isListening ? "Stop voice control" : "Start voice control"
				}
			>
				{isListening ? (
					<BiMicrophoneOff data-cy="mic-off" size={18} />
				) : (
					<BiMicrophone data-cy="mic-on" size={18} />
				)}
				<span className="hidden sm:inline">
					{isListening ? "Listening…" : "Voice Control"}
				</span>
			</button>
		</>
	);
};
 
export default VoiceControlButton;