diff --git a/apps/readest-app/src/__tests__/app/reader/utils/inkAnchoring.test.ts b/apps/readest-app/src/__tests__/app/reader/utils/inkAnchoring.test.ts
new file mode 100644
index 000000000..a6224736e
--- /dev/null
+++ b/apps/readest-app/src/__tests__/app/reader/utils/inkAnchoring.test.ts
@@ -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();
+ });
+});
diff --git a/apps/readest-app/src/__tests__/components/tts/TTSLyricsView.test.tsx b/apps/readest-app/src/__tests__/components/tts/TTSLyricsView.test.tsx
index 15b902c0d..c17029ddf 100644
--- a/apps/readest-app/src/__tests__/components/tts/TTSLyricsView.test.tsx
+++ b/apps/readest-app/src/__tests__/components/tts/TTSLyricsView.test.tsx
@@ -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();
+ 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();
+ 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.
diff --git a/apps/readest-app/src/__tests__/hooks/useTTSControl.test.tsx b/apps/readest-app/src/__tests__/hooks/useTTSControl.test.tsx
index 8bc3b9d96..81a6c1407 100644
--- a/apps/readest-app/src/__tests__/hooks/useTTSControl.test.tsx
+++ b/apps/readest-app/src/__tests__/hooks/useTTSControl.test.tsx
@@ -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();
+ 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)', () => {
diff --git a/apps/readest-app/src/app/reader/components/tts/TTSLyricsView.tsx b/apps/readest-app/src/app/reader/components/tts/TTSLyricsView.tsx
index 2189ecdcb..a0ef2ea71 100644
--- a/apps/readest-app/src/app/reader/components/tts/TTSLyricsView.tsx
+++ b/apps/readest-app/src/app/reader/components/tts/TTSLyricsView.tsx
@@ -53,6 +53,8 @@ const TTSLyricsView = ({
const centersRef = useRef([]);
const heightsRef = useRef([]);
const seekingRef = useRef(false);
+ // Whether the view has parked on the spoken line since it opened.
+ const followedRef = useRef(false);
const idleTimerRef = useRef | null>(null);
const [seekIndex, setSeekIndex] = useState(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 = () => {
diff --git a/apps/readest-app/src/app/reader/hooks/useTTSControl.ts b/apps/readest-app/src/app/reader/hooks/useTTSControl.ts
index fbd946d6e..8f60a4667 100644
--- a/apps/readest-app/src/app/reader/hooks/useTTSControl.ts
+++ b/apps/readest-app/src/app/reader/hooks/useTTSControl.ts
@@ -306,7 +306,10 @@ export const useTTSControl = ({ bookKey, onRequestHidePanel }: UseTTSControlProp
const tryAdopt = async (): Promise => {
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;
diff --git a/apps/readest-app/src/app/reader/utils/inkAnchoring.ts b/apps/readest-app/src/app/reader/utils/inkAnchoring.ts
index 3266f1f79..7ce4e2bf6 100644
--- a/apps/readest-app/src/app/reader/utils/inkAnchoring.ts
+++ b/apps/readest-app/src/app/reader/utils/inkAnchoring.ts
@@ -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();