fix(reader): navigate paragraphs with volume buttons (#7227)

* fix(reader): navigate paragraphs with volume buttons

Route volume-up/down to the paragraph iterator when paragraph mode is
active, while retaining the volume-key setting and active Read Aloud guard.

Verified the regression test failed before the fix in all four horizontal/
vertical and LTR/RTL combinations: expected vi.fn() to be called once, got
0 times. With the fix, the related hardware-key tests passed (27 tests)
on origin/main f88b7451f. TypeScript and Biome passed.

Earlier full suite: 1219 files passed, 4 skipped; 14569 tests passed,
16 skipped. Chrome reader checks passed in desktop, phone, dark and e-ink
modes. Android API 35 emulator with actual adb volume presses passed
paragraph next/previous, setting-off suppression and page navigation after
exit. Android used an equivalent debugger-injected frontend patch in the
installed debug app; a newly built APK was not tested. Playback states were
injected for the TTS guard checks; actual audio playback was not exercised.

Reported by UltraVayne on GitHub (#7209).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(reader): preserve paragraph commands during section changes

Serialize paragraph navigation events so a repeated volume press waits for
the previous section transition and iterator initialization. Discard queued
commands when the effect is cleaned up, including paragraph-mode exit.

Both new next/previous regression cases fail without this change: expected
Second B but received Second A; expected First A but received First B.
The paragraph-mode and volume-key suites pass with the change (68 tests).
TypeScript and Biome checks passed. Real-device re-check of this follow-up
was not run; the section transition is held pending in the regression test.

Reported by CodeRabbit on PR #7227.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(reader): recover paragraph queue after a failed move

Return each queued move's result to its dispatcher while keeping the queue
tail fulfilled, so one rejected move cannot block later paragraph commands.

The new regression injects one iterator failure, verifies that the first
dispatch rejects, then verifies that the next dispatch advances a paragraph.
Without the fix the second dispatch rejects with Paragraph move failed.
The paragraph-mode and volume-key suites pass (69 tests); TypeScript and
Biome pass. This failure path was verified with the hook test, not a device.

Reported by CodeRabbit on PR #7227.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(reader): avoid paragraph queue delays at book boundaries

After awaiting section navigation, skip section-change polling when the
primary document is unchanged. The paginator completes the target document
load before resolving, so a completed no-op needs no six-second wait.

Both new boundary regressions fail without the change: repeated next/prev
commands reach the final 750ms polling delay before allowing a reverse move.
With the fix, reverse navigation succeeds without that polling. All 71
paragraph-mode and volume-key tests pass; TypeScript and Biome pass.
The boundary follow-up was tested with the hook fixture, not on a device.

Reported by CodeRabbit on PR #7227.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(reader): distinguish book boundaries from pending page turns

Use the paginator's atEnd/atStart state before treating an unchanged primary
document as a boundary. Away from a confirmed boundary, retain the wait for
an overlapping page turn to provide the new section document.

Both new overlap regressions fail without this change: expected Second A
but got First B going forward, and expected First B but got Second A going
backward. All 73 paragraph-mode and volume-key tests pass, including the
immediate boundary cases; TypeScript and Biome pass. The overlap was tested
with the hook fixture and was not rechecked on a device.

Reported by CodeRabbit on PR #7227.

Co-Authored-By: Claude Code <noreply@anthropic.com>

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
This commit is contained in:
Huang Xin 2026-11-02 10:33:13 +08:00 • committed by GitHub
parent f88b7451fb
commit a7c168ee54
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 231 additions and 12 deletions

View file

@ -194,6 +194,77 @@ describe('usePagination volume-key interception with TTS (#4691)', () => {
expect(view.next).not.toHaveBeenCalled();
});
test.each([
{ rtl: false, vertical: false },
{ rtl: true, vertical: false },
{ rtl: false, vertical: true },
{ rtl: true, vertical: true },
])('navigates paragraphs instead of pages with volume keys (%j)', async (layout) => {
h.viewSettings = {
volumeKeysToFlip: true,
paragraphMode: { enabled: true },
readingRulerEnabled: true,
...layout,
};
const next = vi.fn();
const prev = vi.fn();
const ruler = vi.fn(() => true);
eventDispatcher.on('paragraph-next', next);
eventDispatcher.on('paragraph-prev', prev);
eventDispatcher.onSync('reading-ruler-move', ruler);
try {
const view = makeView();
const { rerender } = setupWithView(view);
await pressVolumeKey('VolumeDown');
expect(next).toHaveBeenCalledOnce();
expect(next.mock.calls[0]![0].detail).toEqual({ bookKey: BOOK_KEY });
expect(prev).not.toHaveBeenCalled();
await pressVolumeKey('VolumeUp');
expect(prev).toHaveBeenCalledOnce();
expect(prev.mock.calls[0]![0].detail).toEqual({ bookKey: BOOK_KEY });
expect(ruler).not.toHaveBeenCalled();
expect(view.next).not.toHaveBeenCalled();
expect(view.prev).not.toHaveBeenCalled();
next.mockClear();
prev.mockClear();
await emitPlayback('playing');
await pressVolumeKey('VolumeDown');
await pressVolumeKey('VolumeUp');
expect(next).not.toHaveBeenCalled();
expect(prev).not.toHaveBeenCalled();
await emitPlayback('paused');
await pressVolumeKey('VolumeDown');
expect(next).toHaveBeenCalledOnce();
h.viewSettings = { ...h.viewSettings, volumeKeysToFlip: false };
rerender();
await pressVolumeKey('VolumeDown');
await pressVolumeKey('VolumeUp');
expect(next).toHaveBeenCalledOnce();
expect(prev).not.toHaveBeenCalled();
h.viewSettings = {
volumeKeysToFlip: true,
paragraphMode: { enabled: false },
...layout,
};
rerender();
await pressVolumeKey('VolumeDown');
await pressVolumeKey('VolumeUp');
expect(view.next).toHaveBeenCalledOnce();
expect(view.prev).toHaveBeenCalledOnce();
expect(next).toHaveBeenCalledOnce();
expect(prev).not.toHaveBeenCalled();
} finally {
eventDispatcher.off('paragraph-next', next);
eventDispatcher.off('paragraph-prev', prev);
eventDispatcher.offSync('reading-ruler-move', ruler);
}
});
test('page-flips on volume keys when TTS is paused', async () => {
const view = makeView();
setupWithView(view);

View file

@ -12,6 +12,7 @@ import ParagraphOverlay from '@/app/reader/components/paragraph/ParagraphOverlay
import { useParagraphMode } from '@/app/reader/hooks/useParagraphMode';
import type { FoliateView } from '@/types/view';
import { eventDispatcher } from '@/utils/event';
import { ParagraphIterator } from '@/utils/paragraph';
import {
getParagraphActionForKey,
getParagraphActionForZone,
@ -110,6 +111,8 @@ function createMockView(docs: Document[], initialPrimaryIndex: number) {
const renderer = {
primaryIndex: initialPrimaryIndex,
atStart: false,
atEnd: false,
getContents: vi.fn(() => contents),
nextSection: vi.fn(async () => {
renderer.primaryIndex = Math.min(renderer.primaryIndex + 1, contents.length - 1);
@ -241,6 +244,136 @@ describe('paragraph mode', () => {
});
});
it.each([
'next',
'prev',
] as const)('preserves repeated %s paragraph events during a section transition', async (direction) => {
const firstDoc = createDoc('<p>First A</p><p>First B</p>');
const secondDoc = createDoc('<p>Second A</p><p>Second B</p>');
const { view, renderer } = createMockView([firstDoc, secondDoc], direction === 'next' ? 0 : 1);
let finishTransition: (() => void) | undefined;
const transition = direction === 'next' ? renderer.nextSection : renderer.prevSection;
transition.mockImplementation(
() =>
new Promise<void>((resolve) => {
finishTransition = () => {
renderer.primaryIndex = direction === 'next' ? 1 : 0;
resolve();
};
}),
);
const viewRef = { current: view } as React.RefObject<FoliateView | null>;
render(<HookHarness view={viewRef} />);
await waitFor(() => expect(hookApi?.paragraphState.currentRange).toBeTruthy());
if (direction === 'next') {
await act(async () => {
await hookApi?.goToNextParagraph();
});
}
let firstPress = Promise.resolve();
let secondPress = Promise.resolve();
await act(async () => {
firstPress = eventDispatcher.dispatch(`paragraph-${direction}`, { bookKey: 'book-1' });
});
await waitFor(() => expect(transition).toHaveBeenCalledOnce());
await act(async () => {
secondPress = eventDispatcher.dispatch(`paragraph-${direction}`, { bookKey: 'book-1' });
finishTransition!();
await Promise.all([firstPress, secondPress]);
});
await waitFor(() => {
expect(hookApi?.paragraphState.currentRange?.toString()).toBe(
direction === 'next' ? 'Second B' : 'First A',
);
});
expect(transition).toHaveBeenCalledOnce();
});
it.each([
'next',
'prev',
] as const)('does not wait on repeated %s book-boundary events before reversing', async (direction) => {
const timers = vi
.spyOn(globalThis, 'setTimeout')
.mockImplementation((handler, timeout) =>
realSetTimeout(handler, typeof timeout === 'number' && timeout < 1000 ? 0 : timeout),
);
const doc = createDoc('<p>First</p><p>Last</p>');
const { view, renderer } = createMockView([doc], 0);
renderer.atStart = true;
renderer.atEnd = true;
render(<HookHarness view={{ current: view }} />);
await waitFor(() => expect(hookApi?.paragraphState.currentRange).toBeTruthy());
if (direction === 'next') {
await act(async () => {
await hookApi?.goToNextParagraph();
});
}
timers.mockClear();
await act(async () => {
await Promise.all([
eventDispatcher.dispatch(`paragraph-${direction}`, { bookKey: 'book-1' }),
eventDispatcher.dispatch(`paragraph-${direction}`, { bookKey: 'book-1' }),
eventDispatcher.dispatch(direction === 'next' ? 'paragraph-prev' : 'paragraph-next', {
bookKey: 'book-1',
}),
]);
});
expect(hookApi?.paragraphState.currentRange?.toString()).toBe(
direction === 'next' ? 'First' : 'Last',
);
expect(timers).not.toHaveBeenCalledWith(expect.any(Function), 750);
});
it.each([
'next',
'prev',
] as const)('waits for an existing page turn when the %s section move returns early', async (direction) => {
const firstDoc = createDoc('<p>First A</p><p>First B</p>');
const secondDoc = createDoc('<p>Second A</p><p>Second B</p>');
const { view, renderer } = createMockView([firstDoc, secondDoc], direction === 'next' ? 0 : 1);
const transition = direction === 'next' ? renderer.nextSection : renderer.prevSection;
transition.mockImplementation(async () => {
setTimeout(() => {
renderer.primaryIndex = direction === 'next' ? 1 : 0;
}, 0);
});
render(<HookHarness view={{ current: view }} />);
await waitFor(() => expect(hookApi?.paragraphState.currentRange).toBeTruthy());
if (direction === 'next') {
await act(async () => {
await hookApi?.goToNextParagraph();
});
}
await act(async () => {
await eventDispatcher.dispatch(`paragraph-${direction}`, { bookKey: 'book-1' });
});
expect(hookApi?.paragraphState.currentRange?.toString()).toBe(
direction === 'next' ? 'Second A' : 'First B',
);
});
it('reports a failed paragraph event and still runs the next event', async () => {
const doc = createDoc('<p>First</p><p>Second</p><p>Third</p>');
const { view } = createMockView([doc], 0);
render(<HookHarness view={{ current: view }} />);
await waitFor(() => expect(hookApi?.paragraphState.currentRange?.toString()).toBe('First'));
const failure = new Error('Paragraph move failed');
vi.spyOn(ParagraphIterator.prototype, 'next').mockImplementationOnce(() => {
throw failure;
});
await act(async () => {
await expect(eventDispatcher.dispatch('paragraph-next', { bookKey: 'book-1' })).rejects.toBe(
failure,
);
});
await act(async () => {
await eventDispatcher.dispatch('paragraph-next', { bookKey: 'book-1' });
});
expect(hookApi?.paragraphState.currentRange?.toString()).toBe('Second');
});
it('moves across the chunks of a section rendered in chunks', async () => {
// foliate-js renders a huge section as chunk documents that share its
// spine index; each holds hidden placeholders for the other chunks.

View file

@ -460,6 +460,15 @@ export const usePagination = (
) {
const { keyName } = msg.detail;
setHoveredBookKey('');
if (
viewSettings.paragraphMode?.enabled &&
(keyName === 'VolumeUp' || keyName === 'VolumeDown')
) {
eventDispatcher.dispatch(keyName === 'VolumeUp' ? 'paragraph-prev' : 'paragraph-next', {
bookKey,
});
return;
}
if (keyName === 'VolumeUp') {
if (viewSettings.readingRulerEnabled && dispatchReadingRulerMove('up')) {
return;

View file

@ -515,7 +515,9 @@ export const useParagraphMode = ({ bookKey, viewRef }: UseParagraphModeProps) =>
try {
await view.renderer.nextSection?.();
const newSectionReady = await waitForNewSection(oldDoc);
const newSectionReady =
(getPrimaryContent()?.doc !== oldDoc || !view.renderer.atEnd) &&
(await waitForNewSection(oldDoc));
if (!newSectionReady) {
pendingNavigationRef.current = null;
@ -575,7 +577,9 @@ export const useParagraphMode = ({ bookKey, viewRef }: UseParagraphModeProps) =>
try {
await view.renderer.prevSection?.();
const newSectionReady = await waitForNewSection(oldDoc);
const newSectionReady =
(getPrimaryContent()?.doc !== oldDoc || !view.renderer.atStart) &&
(await waitForNewSection(oldDoc));
if (!newSectionReady) {
pendingNavigationRef.current = null;
@ -772,23 +776,25 @@ export const useParagraphMode = ({ bookKey, viewRef }: UseParagraphModeProps) =>
}
};
const handleNext = (event: CustomEvent) => {
if (event.detail?.bookKey === bookKeyRef.current && paragraphConfig.enabled) {
goToNextParagraph();
}
};
const handlePrev = (event: CustomEvent) => {
if (event.detail?.bookKey === bookKeyRef.current && paragraphConfig.enabled) {
goToPrevParagraph();
}
let active = true;
let navigation = Promise.resolve();
const enqueueNavigation = (event: CustomEvent, move: () => Promise<boolean>) => {
if (event.detail?.bookKey !== bookKeyRef.current || !paragraphConfig.enabled) return;
const result = navigation.then(async () => {
if (active) await move();
});
navigation = result.catch(() => {});
return result;
};
const handleNext = (event: CustomEvent) => enqueueNavigation(event, goToNextParagraph);
const handlePrev = (event: CustomEvent) => enqueueNavigation(event, goToPrevParagraph);
eventDispatcher.on('toggle-paragraph-mode', handleToggle);
eventDispatcher.on('paragraph-next', handleNext);
eventDispatcher.on('paragraph-prev', handlePrev);
return () => {
active = false;
eventDispatcher.off('toggle-paragraph-mode', handleToggle);
eventDispatcher.off('paragraph-next', handleNext);
eventDispatcher.off('paragraph-prev', handlePrev);