mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-12-17 17:00:15 +01:00
* refactor: do not call await inside useCallbacks, rely on updates for dropdown * fix: remember last selected voice * refactor: Update Speech component to use TypeScript in useCallback * refactor: Update Dropdown component styles to match header theme
67 lines
1.8 KiB
TypeScript
67 lines
1.8 KiB
TypeScript
import { useRecoilState } from 'recoil';
|
|
import { useState, useEffect, useCallback } from 'react';
|
|
import store from '~/store';
|
|
|
|
interface VoiceOption {
|
|
value: string;
|
|
label: string;
|
|
}
|
|
|
|
function useTextToSpeechBrowser() {
|
|
const [cloudBrowserVoices] = useRecoilState(store.cloudBrowserVoices);
|
|
const [isSpeaking, setIsSpeaking] = useState(false);
|
|
const [voiceName] = useRecoilState(store.voice);
|
|
const [voices, setVoices] = useState<VoiceOption[]>([]);
|
|
|
|
const updateVoices = useCallback(() => {
|
|
const availableVoices = window.speechSynthesis
|
|
.getVoices()
|
|
.filter((v) => cloudBrowserVoices || v.localService === true);
|
|
|
|
const voiceOptions: VoiceOption[] = availableVoices.map((v) => ({
|
|
value: v.name,
|
|
label: v.name,
|
|
}));
|
|
|
|
setVoices(voiceOptions);
|
|
}, [cloudBrowserVoices]);
|
|
|
|
useEffect(() => {
|
|
if (window.speechSynthesis.getVoices().length) {
|
|
updateVoices();
|
|
} else {
|
|
window.speechSynthesis.onvoiceschanged = updateVoices;
|
|
}
|
|
|
|
return () => {
|
|
window.speechSynthesis.onvoiceschanged = null;
|
|
};
|
|
}, [updateVoices]);
|
|
|
|
const generateSpeechLocal = (text: string) => {
|
|
const synth = window.speechSynthesis;
|
|
const voice = voices.find((v) => v.value === voiceName);
|
|
|
|
if (!voice) {
|
|
return;
|
|
}
|
|
|
|
synth.cancel();
|
|
const utterance = new SpeechSynthesisUtterance(text);
|
|
utterance.voice = synth.getVoices().find((v) => v.name === voice.value) || null;
|
|
utterance.onend = () => {
|
|
setIsSpeaking(false);
|
|
};
|
|
setIsSpeaking(true);
|
|
synth.speak(utterance);
|
|
};
|
|
|
|
const cancelSpeechLocal = () => {
|
|
window.speechSynthesis.cancel();
|
|
setIsSpeaking(false);
|
|
};
|
|
|
|
return { generateSpeechLocal, cancelSpeechLocal, isSpeaking, voices };
|
|
}
|
|
|
|
export default useTextToSpeechBrowser;
|