tts: more robust way to save last speaking location for tts (#1293)

This commit is contained in:
Huang Xin
2025-05-31 19:34:35 +08:00
committed by GitHub
parent 69c503026a
commit 32f9346f84
3 changed files with 23 additions and 11 deletions
@@ -25,7 +25,8 @@ const TTSControl = () => {
const _ = useTranslation();
const { appService } = useEnv();
const { getBookData } = useBookDataStore();
const { getView, getProgress, getViewSettings, setTTSEnabled } = useReaderStore();
const { getView, getProgress, getViewSettings } = useReaderStore();
const { setViewSettings, setTTSEnabled } = useReaderStore();
const [bookKey, setBookKey] = useState<string>('');
const [ttsLang, setTtsLang] = useState<string>('en');
const [isPlaying, setIsPlaying] = useState(false);
@@ -118,9 +119,27 @@ const TTSControl = () => {
}
};
const handleHighlightMark = (e: Event) => {
const range = (e as CustomEvent<Range>).detail;
const view = getView(bookKey);
const progress = getProgress(bookKey);
const viewSettings = getViewSettings(bookKey);
if (!range || !view || !progress || !viewSettings) return;
const { location } = progress;
const { index } = view.resolveCFI(location);
const cfi = view?.getCFI(index, range);
if (cfi) {
viewSettings.ttsLocation = cfi || '';
setViewSettings(bookKey, viewSettings);
}
};
ttsController.addEventListener('tts-speak-mark', handleSpeakMark);
ttsController.addEventListener('tts-highlight-mark', handleHighlightMark);
return () => {
ttsController.removeEventListener('tts-speak-mark', handleSpeakMark);
ttsController.removeEventListener('tts-highlight-mark', handleHighlightMark);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ttsController, bookKey]);
@@ -12,7 +12,7 @@ export const useTextSelector = (
handleDismissPopup: () => void,
) => {
const { getBookData } = useBookDataStore();
const { getView, getViewState, getViewSettings, setViewSettings } = useReaderStore();
const { getView, getViewSettings } = useReaderStore();
const view = getView(bookKey);
const bookData = getBookData(bookKey)!;
const viewSettings = getViewSettings(bookKey)!;
@@ -84,14 +84,6 @@ export const useTextSelector = (
if (isTouchStarted.current && osPlatform === 'android') {
makeSelection(sel, index, false);
}
if (!isTouchStarted.current && getViewState(bookKey)?.ttsEnabled) {
const viewSettings = getViewSettings(bookKey)!;
const cfi = view?.getCFI(index, sel.getRangeAt(0));
if (cfi) {
viewSettings.ttsLocation = cfi || '';
setViewSettings(bookKey, viewSettings);
}
}
isUpToPopup.current = true;
};
const handlePointerup = (doc: Document, index: number) => {
@@ -130,7 +130,8 @@ export class TTSController extends EventTarget {
return;
}
if (mark && this.state === 'playing') {
this.view.tts?.setMark(mark);
const range = this.view.tts?.setMark(mark);
this.dispatchEvent(new CustomEvent('tts-highlight-mark', { detail: range }));
}
lastCode = code;
}