mirror of
https://github.com/readest/readest.git
synced 2026-11-29 19:02:28 +00:00
fix(tts): keep Read Aloud and its highlights intact after the sign-in detour (#6758)
* fix(reader): don't crash re-anchoring ink while a section frame reloads Returning to the reader from another route (e.g. back from the sign-in page opened by a locked TTS voice) re-attaches the still-open view, and its section iframe reloads. For a moment the section document has no root element, so createInkAnchoring threw destructuring documentElement; the error page then hard-reloaded the whole app, which stopped Read Aloud. Return null until the document has a root; the re-anchor effect runs again on the next layout change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(tts): adopt the live session only into the view on screen When the reader remounts under the same book key, the store keeps the previous, detached foliate view until the new one finishes opening. The seamless-reattach poll adopted the background TTS session into that detached view, so every sentence and word highlight was drawn off screen while the page still followed the voice. Adopt only a connected view; the existing 300ms retry picks up the new view once it is registered. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(tts): open the player lyrics on the spoken line without a scroll animation Opening the full player glided the lyrics from the top to the spoken sentence whenever it sat less than two viewports down, a long animation on every open. Land the first follow scroll outright; moving on to the next sentence still glides. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(tts): keep the instant first lyric scroll until the lines have loaded The spoken index arrives before the chapter's lyric lines load. With no lines yet the follow effect still ran, consumed the first-scroll flag on a no-op, and the real first scroll then glided. Wait until the index points at a loaded line. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
43c55a8c16
commit
e4af649128
6 changed files with 130 additions and 43 deletions
|
|
@ -0,0 +1,21 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { createInkAnchoring } from '@/app/reader/utils/inkAnchoring';
|
||||
import type { FoliateView } from '@/types/view';
|
||||
|
||||
const page = { left: 0, top: 0, width: 400, height: 600 };
|
||||
|
||||
describe('createInkAnchoring', () => {
|
||||
// Returning to the reader (e.g. back from the sign-in page) re-attaches the
|
||||
// still-open view, whose section iframe reloads: for a moment its document
|
||||
// has no root element yet.
|
||||
it('returns null while the section document has no root element', () => {
|
||||
const frame = { getBoundingClientRect: () => new DOMRect(0, 0, 400, 600) };
|
||||
const doc = { documentElement: null, defaultView: { frameElement: frame } };
|
||||
const view = {
|
||||
renderer: { getContents: () => [{ index: 3, doc }] },
|
||||
} as unknown as FoliateView;
|
||||
|
||||
expect(createInkAnchoring(view, 3, page)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
|
@ -152,6 +152,28 @@ describe('TTSLyricsView', () => {
|
|||
);
|
||||
});
|
||||
|
||||
test('opens onto the spoken line outright, then glides to the next', () => {
|
||||
// Line 2 is only half a viewport down, yet opening the player must not
|
||||
// animate the scroll to it.
|
||||
const { rerender } = renderView({ activeIndex: 2 });
|
||||
expect(scroller().scrollTo).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ top: 100, behavior: 'auto' }),
|
||||
);
|
||||
rerender(<TTSLyricsView {...defaults} activeIndex={3} />);
|
||||
expect(scroller().scrollTo).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ top: 140, behavior: 'smooth' }),
|
||||
);
|
||||
});
|
||||
|
||||
test('still opens outright when the lines arrive after the spoken index', () => {
|
||||
// The spoken index is known at once; the chapter's lines load after it.
|
||||
const { rerender } = renderView({ lines: [], activeIndex: 2 });
|
||||
rerender(<TTSLyricsView {...defaults} activeIndex={2} />);
|
||||
expect(scroller().scrollTo).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ top: 100, behavior: 'auto' }),
|
||||
);
|
||||
});
|
||||
|
||||
test('does not animate the follow scroll on e-ink', () => {
|
||||
const { rerender } = renderView({ activeIndex: 0, isEink: true });
|
||||
// Past the initial snap: every later move stays instant too.
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ vi.mock('@/store/themeStore', () => ({
|
|||
}));
|
||||
|
||||
const mockView = {
|
||||
isConnected: true,
|
||||
book: { primaryLanguage: 'en', sections: [{ id: 0 }] },
|
||||
renderer: {
|
||||
getContents: () => [{ index: 0, doc: document as unknown as Document }],
|
||||
|
|
@ -1215,43 +1216,45 @@ describe('useTTSControl background session lifecycle', () => {
|
|||
expect(mockSessionManager.stopActive).toHaveBeenCalledWith('replaced');
|
||||
});
|
||||
|
||||
const makeLiveController = () => ({
|
||||
kind: 'tts',
|
||||
state: 'playing',
|
||||
terminated: false,
|
||||
isViewAttached: false,
|
||||
shutdown: vi.fn(),
|
||||
detachView: vi.fn(),
|
||||
attachView: vi.fn().mockResolvedValue(undefined),
|
||||
getSpeakingLang: vi.fn().mockReturnValue('en'),
|
||||
getCurrentHighlightCfi: vi.fn().mockReturnValue(null),
|
||||
getCurrentPlaybackCfi: vi.fn().mockReturnValue(null),
|
||||
getSectionIndex: vi.fn().mockReturnValue(0),
|
||||
isSoundingSentenceOnScreen: vi.fn().mockReturnValue(false),
|
||||
getSpokenSentence: vi.fn().mockReturnValue(null),
|
||||
updateHighlightOptions: vi.fn(),
|
||||
setHighlightGranularity: vi.fn(),
|
||||
setSkipInlineAnnotations: vi.fn(),
|
||||
setCustomTTSServices: vi.fn(),
|
||||
drawLoopRange: vi.fn(),
|
||||
getVoiceId: vi.fn().mockReturnValue(''),
|
||||
setTargetLang: vi.fn(),
|
||||
setLang: vi.fn(),
|
||||
setRate: vi.fn(),
|
||||
pause: vi.fn().mockResolvedValue(true),
|
||||
resume: vi.fn().mockResolvedValue(true),
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
stop: vi.fn().mockResolvedValue(undefined),
|
||||
forward: vi.fn().mockResolvedValue(undefined),
|
||||
backward: vi.fn().mockResolvedValue(undefined),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
redispatchPosition: vi.fn(),
|
||||
usesAudioTransport: vi.fn().mockReturnValue(false),
|
||||
supportsLyrics: vi.fn().mockReturnValue(true),
|
||||
isBuffering: vi.fn().mockReturnValue(false),
|
||||
});
|
||||
|
||||
it('adopts a live session for the same book without constructing a controller', async () => {
|
||||
const liveController = {
|
||||
kind: 'tts',
|
||||
state: 'playing',
|
||||
terminated: false,
|
||||
isViewAttached: false,
|
||||
shutdown: vi.fn(),
|
||||
detachView: vi.fn(),
|
||||
attachView: vi.fn().mockResolvedValue(undefined),
|
||||
getSpeakingLang: vi.fn().mockReturnValue('en'),
|
||||
getCurrentHighlightCfi: vi.fn().mockReturnValue(null),
|
||||
getCurrentPlaybackCfi: vi.fn().mockReturnValue(null),
|
||||
getSectionIndex: vi.fn().mockReturnValue(0),
|
||||
isSoundingSentenceOnScreen: vi.fn().mockReturnValue(false),
|
||||
getSpokenSentence: vi.fn().mockReturnValue(null),
|
||||
updateHighlightOptions: vi.fn(),
|
||||
setHighlightGranularity: vi.fn(),
|
||||
setSkipInlineAnnotations: vi.fn(),
|
||||
setCustomTTSServices: vi.fn(),
|
||||
drawLoopRange: vi.fn(),
|
||||
getVoiceId: vi.fn().mockReturnValue(''),
|
||||
setTargetLang: vi.fn(),
|
||||
setLang: vi.fn(),
|
||||
setRate: vi.fn(),
|
||||
pause: vi.fn().mockResolvedValue(true),
|
||||
resume: vi.fn().mockResolvedValue(true),
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
stop: vi.fn().mockResolvedValue(undefined),
|
||||
forward: vi.fn().mockResolvedValue(undefined),
|
||||
backward: vi.fn().mockResolvedValue(undefined),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
redispatchPosition: vi.fn(),
|
||||
usesAudioTransport: vi.fn().mockReturnValue(false),
|
||||
supportsLyrics: vi.fn().mockReturnValue(true),
|
||||
isBuffering: vi.fn().mockReturnValue(false),
|
||||
};
|
||||
const liveController = makeLiveController();
|
||||
mockSessionManager.getSessionByHash.mockReturnValue({
|
||||
bookHash: 'book',
|
||||
bookKey: 'book-old',
|
||||
|
|
@ -1272,6 +1275,37 @@ describe('useTTSControl background session lifecycle', () => {
|
|||
);
|
||||
expect(liveController.setSkipInlineAnnotations).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
// Back from another route the reader remounts under the same book key; the
|
||||
// store still holds the previous, detached view until the new one opens.
|
||||
// Attaching to that one would draw every highlight off screen.
|
||||
it('waits for the view on screen instead of adopting into a detached one', async () => {
|
||||
const liveController = makeLiveController();
|
||||
mockSessionManager.getSessionByHash.mockReturnValue({
|
||||
bookHash: 'book',
|
||||
bookKey: 'book-1',
|
||||
controller: liveController,
|
||||
});
|
||||
mockView.isConnected = false;
|
||||
try {
|
||||
render(<Harness />);
|
||||
await act(async () => {
|
||||
for (let i = 0; i < 10; i++) await Promise.resolve();
|
||||
});
|
||||
expect(liveController.attachView).not.toHaveBeenCalled();
|
||||
|
||||
mockView.isConnected = true;
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 350));
|
||||
});
|
||||
expect(liveController.attachView).toHaveBeenCalledWith(
|
||||
mockView,
|
||||
expect.objectContaining({ bookKey: 'book-1' }),
|
||||
);
|
||||
} finally {
|
||||
mockView.isConnected = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('useTTSControl gap control (handleSetSentenceGap / handleSupportsGapControl)', () => {
|
||||
|
|
|
|||
|
|
@ -53,6 +53,8 @@ const TTSLyricsView = ({
|
|||
const centersRef = useRef<number[]>([]);
|
||||
const heightsRef = useRef<number[]>([]);
|
||||
const seekingRef = useRef(false);
|
||||
// Whether the view has parked on the spoken line since it opened.
|
||||
const followedRef = useRef(false);
|
||||
const idleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const [seekIndex, setSeekIndex] = useState<number | null>(null);
|
||||
|
|
@ -111,7 +113,8 @@ const TTSLyricsView = ({
|
|||
useEffect(() => {
|
||||
if (seekIndex !== null || pending !== null) return;
|
||||
const el = scrollerRef.current;
|
||||
if (!el || activeIndex < 0) return;
|
||||
// The spoken index can arrive before the chapter's lines load.
|
||||
if (!el || activeIndex < 0 || activeIndex >= lines.length) return;
|
||||
// Nothing to aim at until the lines have been measured: scrolling on the
|
||||
// pre-measure pass would just land at zero.
|
||||
if (centersRef.current.length !== lines.length) return;
|
||||
|
|
@ -122,15 +125,18 @@ const TTSLyricsView = ({
|
|||
el.clientHeight,
|
||||
);
|
||||
// Glide between neighbouring sentences the way a music player does, but
|
||||
// land a long move outright: opening onto the middle of a chapter, or
|
||||
// jumping chapters, is thousands of pixels, and animating that is a blur
|
||||
// past text nobody is reading. E-ink cannot animate at all — a smooth
|
||||
// land the first move and any long one outright: opening the player, or
|
||||
// jumping chapters, should show the spoken line at once, not a scroll
|
||||
// through text nobody is reading. E-ink cannot animate at all — a smooth
|
||||
// scroll there is a stutter of full refreshes.
|
||||
const opening = !followedRef.current;
|
||||
followedRef.current = true;
|
||||
const distance = Math.abs(top - el.scrollTop);
|
||||
// Already parked there — re-issuing the scroll would only re-arm an
|
||||
// animation over nothing.
|
||||
if (distance < 1) return;
|
||||
el.scrollTo?.({ top, behavior: distance > el.clientHeight * 2 || isEink ? 'auto' : 'smooth' });
|
||||
const instant = opening || distance > el.clientHeight * 2 || isEink;
|
||||
el.scrollTo?.({ top, behavior: instant ? 'auto' : 'smooth' });
|
||||
}, [activeIndex, seekIndex, pending, isEink, geometry, halfHeight, lines]);
|
||||
|
||||
const clearIdleTimer = () => {
|
||||
|
|
|
|||
|
|
@ -306,7 +306,10 @@ export const useTTSControl = ({ bookKey, onRequestHidePanel }: UseTTSControlProp
|
|||
const tryAdopt = async (): Promise<boolean> => {
|
||||
if (cancelled || isStartingTTSRef.current) return false;
|
||||
const view = getView(bookKey);
|
||||
if (!view) return false;
|
||||
// A remount under the same key (back from another route) still holds the
|
||||
// previous, detached view until the new one opens: highlights drawn
|
||||
// there never show.
|
||||
if (!view?.isConnected) return false;
|
||||
isStartingTTSRef.current = true;
|
||||
try {
|
||||
const controller = sessionController;
|
||||
|
|
|
|||
|
|
@ -106,7 +106,8 @@ export const createInkAnchoring = (
|
|||
): InkAnchoring | null => {
|
||||
const doc = view.renderer.getContents().find((c) => c.index === sectionIndex)?.doc;
|
||||
const frame = doc?.defaultView?.frameElement;
|
||||
if (!doc || !frame) return null;
|
||||
// A re-attached view's section frame reloads, its document briefly rootless.
|
||||
if (!doc?.documentElement || !frame) return null;
|
||||
|
||||
// Section document coordinates <-> main-window coordinates.
|
||||
const frameRect = frame.getBoundingClientRect();
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue