fix(reader): highlight continued multi-paragraph dialogue (#7238)

* fix(reader): highlight continued multi-paragraph dialogue

Highlight an unclosed quote through the end of its paragraph when the
next text block starts with the same opening mark. Preserve closed-quote
matching, length limits, inline markup, and unmatched-quote fallback;
skipped code-only paragraphs still break adjacency.

Verification: 99 tests passed across dialogue-highlight, cfi, epubcfi-skip,
and epubcfi-translation-stability. pnpm lint, changed-file formatting, and
git diff --check passed. The new continuation tests fail without the fix:
expected all three paragraphs, received only the final paragraph.

Compared the original and fixed matchers in the same imported EPUB in an
Android 15 / WebView 124 reader: both double- and single-quoted speeches
now mark every paragraph while narration remains unmarked. Android 16,
the reporter's book, and the full visual mode matrix were not verified.
The full unit suite is left to the pre-push hook and CI.

Reported by lambda3141 on GitHub.

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

* fix(reader): preserve paragraph prefixes in dialogue continuation

Use the first non-whitespace character of each text block, including
skipped text, when checking whether the next paragraph reopens a quote.
A leading code example must not make an unmatched earlier paragraph
appear to be continued dialogue.

Verification: both new leading-code fallback cases failed before this
correction (expected true to be false for highlighting Unclosed), then
passed. All 101 related dialogue and CFI tests, pnpm lint, changed-file
formatting, and git diff --check passed. Lint reports one informational
finding in unchanged nativePageTurn.ts. This correction was not separately
rechecked in the Android app; the original continuation behavior was
verified there before the initial commit.

Reported by lambda3141 on GitHub.

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

* fix(reader): distinguish skipped dialogue prefixes

Ignore non-rendered script and style text when collecting paragraph
boundaries. Require a continuation's paragraph-leading quotation mark
to come from eligible text, so quotes inside skipped code remain barriers.

Verification: four new tests failed before this correction: style/script
cases received only the final paragraph, and skipped-code quote cases
incorrectly highlighted Unclosed. All 105 related dialogue and CFI tests
pass after the fix. pnpm lint, changed-file formatting and git diff --check
passed, with one informational lint finding in unchanged nativePageTurn.ts.
These edge cases were not separately checked in the Android app.

Reported by lambda3141 on GitHub.

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 14:30:04 +08:00 • committed by GitHub
parent a2dd013a47
commit cce0895cce
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 134 additions and 11 deletions

View file

@ -443,6 +443,88 @@ describe('manageDialogueHighlight', () => {
expect(spans).toEqual(quotes);
});
it.each([
['“', '”'],
['‘', '’'],
['„', '“'],
['«', '»'],
['「', '」'],
['『', '』'],
])('wraps every paragraph of a speech continued with %s', (open, close) => {
const first = `${open}First paragraph, with no closing mark.`;
const second = `${open}Second paragraph, still no closing mark.`;
const last = `${open}Final paragraph, which closes the speech.${close}`;
const doc = makeDoc(
`<p>Narration before ${first}</p>\n <p> ${second}</p>\n <p>${last} Narration after.</p>`,
);
manageDialogueHighlight(doc, makeViewSettings({ dialogueHighlight: true }));
const spans = [...doc.querySelectorAll(`.${DIALOGUE_SPAN_CLASS}`)].map((s) => s.textContent);
expect(spans).toEqual([first, second, last]);
});
it.each([
'<style>p { color: black }</style>',
'<script>const example = 1;</script>',
])('ignores non-rendered text between continued paragraphs: %s', (between) => {
const doc = makeDoc(`<p>“First.</p>${between}<p>“Second.”</p>`);
manageDialogueHighlight(doc, makeViewSettings({ dialogueHighlight: true }));
const spans = [...doc.querySelectorAll(`.${DIALOGUE_SPAN_CLASS}`)].map((s) => s.textContent);
expect(spans).toEqual(['“First.', '“Second.”']);
});
it('keeps inline markup and apostrophes in continued single-quoted dialogue', () => {
const doc = makeDoc(
`<p>‘We’re going <em>home</em> with their boots.</p>` +
`<p><b>‘We’ll</b> be there soon.’ Narration.</p>`,
);
const original = doc.body.innerHTML;
const settings = makeViewSettings({ dialogueHighlight: true });
manageDialogueHighlight(doc, settings);
manageDialogueHighlight(doc, settings);
const spans = [...doc.querySelectorAll(`.${DIALOGUE_SPAN_CLASS}`)].map((s) => s.textContent);
expect(spans).toEqual([
'‘We’re going ',
'home',
' with their boots.',
'‘We’ll',
' be there soon.’',
]);
expect(
[...doc.querySelectorAll(`.${DIALOGUE_SPAN_CLASS}`)].every((s) => s.hasAttribute('cfi-skip')),
).toBe(true);
clearDialogueHighlight(doc);
expect(doc.body.innerHTML).toBe(original);
});
it.each([
'<p>“Unclosed.</p><p>Narration.</p><p>“Later.”</p>',
'<p>“Unclosed.</p><p><code>Narration.</code></p><p>“Later.”</p>',
'<p>“Unclosed.</p><p><code>Example:</code>“Later.”</p>',
'<p>“Unclosed.</p><p><code>“Example.”</code></p>',
'<p>“Unclosed.</p><p><code>“Example.”</code>“Later.”</p>',
'<p>“Unclosed.</p><p> <code>Example:</code> “Later.”</p>',
'<p>“Unclosed.</p><p>‘Different marks.’</p>',
'<p>“Unclosed.\n“Another line.”</p>',
'<p>“Closed.” Narration.</p><p>“Next.”</p>',
'<p>‘Closed’ Narration.</p><p>‘Next.’</p>',
'<p>“Unclosed.</p><p>Narration “quoted”.</p>',
])('leaves the unmatched quote fallback unchanged: %s', (html) => {
const doc = makeDoc(html);
manageDialogueHighlight(doc, makeViewSettings({ dialogueHighlight: true }));
const spans = [...doc.querySelectorAll(`.${DIALOGUE_SPAN_CLASS}`)].map((s) => s.textContent);
expect(spans.some((text) => text?.includes('Unclosed'))).toBe(false);
expect(spans.some((text) => text?.includes('Narration'))).toBe(false);
});
it('keeps the length limits for continued dialogue', () => {
const doc = makeDoc(
`<p>“${'x'.repeat(2100)}</p><p>“Next.”</p>` + `<p>‘${'x'.repeat(310)}</p><p>‘Next.’</p>`,
);
manageDialogueHighlight(doc, makeViewSettings({ dialogueHighlight: true }));
const spans = [...doc.querySelectorAll(`.${DIALOGUE_SPAN_CLASS}`)].map((s) => s.textContent);
expect(spans).toEqual(['“Next.”', '‘Next.’']);
});
it('does not let an unclosed quote swallow the next one', () => {
const doc = makeDoc(`<p>“Wait, she said.</p><p>He answered “fine” and left.</p>`);
manageDialogueHighlight(doc, makeViewSettings({ dialogueHighlight: true }));

View file

@ -48,6 +48,12 @@ const DIALOGUE_PATTERN =
const NESTED_DIALOGUE_PATTERN =
/“[^“”\n]*(?:“[^“”\n]*”[^“”\n]*)+”|„[^„“\n]*(?:„[^„“\n]*“[^„“\n]*)+“|«[^«»\n]*(?:«[^«»\n]*»[^«»\n]*)+»/gu;
// An unclosed quote may run to the end of its block when the next block
// starts with the same opening mark. Keep the existing closing-quote rules:
// only apostrophes within words are unambiguously part of a single quote.
const CONTINUED_DIALOGUE_PATTERN =
/“[^“”"]+$|„[^„“"]+$|«[^«»]+$|「[^「」]+$|『[^『』]+$|‘(?:[^‘’]|’(?=\p{L}))+$/gu;
const MAX_QUOTE_LENGTH = 2048;
// Paragraph-leading dashes marking dialogue lines (French/Russian/CJK style).
@ -64,6 +70,8 @@ const isSkipped = (node: Text): boolean => {
};
type TextEntry = { node: Text; start: number; end: number };
type Region = { start: number; end: number };
type TextBlock = Region & { firstCharacter: string; firstCharacterEligible: boolean };
const BLOCK_SELECTOR =
'p, div, li, blockquote, dd, dt, h1, h2, h3, h4, h5, h6, td, th, caption, figcaption, section, article, aside, body';
@ -72,33 +80,66 @@ const BLOCK_SELECTOR =
// <br> and inline boundaries contribute zero characters, so a match range can
// transparently cross them and is mapped back to node slices below; a block
// boundary contributes a newline that belongs to no node.
const collectEntries = (doc: Document): { entries: TextEntry[]; text: string } => {
const collectEntries = (
doc: Document,
): { entries: TextEntry[]; text: string; blocks: TextBlock[] } => {
const showText = doc.defaultView?.NodeFilter.SHOW_TEXT ?? 4;
const walker = doc.createTreeWalker(doc.body ?? doc.documentElement, showText);
const entries: TextEntry[] = [];
const blocks: TextBlock[] = [];
let text = '';
let block: Element | null = null;
let node = walker.nextNode() as Text | null;
let textBlock: Element | null = null;
while (node) {
if (!isSkipped(node)) {
const content = node.textContent ?? '';
if (content) {
const nodeBlock = node.parentElement!.closest(BLOCK_SELECTOR);
const content = node.textContent ?? '';
if (content && !node.parentElement?.closest('script, style')) {
const nodeBlock = node.parentElement?.closest(BLOCK_SELECTOR) ?? null;
if (blocks.length === 0 || nodeBlock !== textBlock) {
blocks.push({
start: text.length,
end: text.length,
firstCharacter: '',
firstCharacterEligible: false,
});
}
textBlock = nodeBlock;
const currentBlock = blocks[blocks.length - 1]!;
const eligible = !isSkipped(node);
if (!currentBlock.firstCharacter) {
currentBlock.firstCharacter = content.trimStart().charAt(0);
currentBlock.firstCharacterEligible = eligible;
}
if (eligible) {
if (block && nodeBlock !== block) text += '\n';
if (currentBlock.start === currentBlock.end) currentBlock.start = text.length;
block = nodeBlock;
entries.push({ node, start: text.length, end: text.length + content.length });
text += content;
currentBlock.end = text.length;
}
}
node = walker.nextNode() as Text | null;
}
return { entries, text };
return { entries, text, blocks };
};
type Region = { start: number; end: number };
const findRegions = (text: string): Region[] => {
const findRegions = (text: string, blocks: TextBlock[]): Region[] => {
const raw: Region[] = [];
// Whitespace between elements is not a paragraph. Include skipped text in
// the leading character so code cannot hide narration before an opening mark.
const paragraphs = blocks.filter((block) => block.firstCharacter);
for (let i = 0; i < paragraphs.length - 1; i++) {
const block = paragraphs[i]!;
const next = paragraphs[i + 1]!;
const content = text.slice(block.start, block.end).trimEnd();
CONTINUED_DIALOGUE_PATTERN.lastIndex = 0;
const match = CONTINUED_DIALOGUE_PATTERN.exec(content);
if (!match || !next.firstCharacterEligible || match[0][0] !== next.firstCharacter) continue;
const limit = match[0][0] === '‘' ? 301 : MAX_QUOTE_LENGTH;
if (match[0].length > limit) continue;
raw.push({ start: block.start + match.index, end: block.start + content.length });
}
for (const pattern of [DIALOGUE_PATTERN, NESTED_DIALOGUE_PATTERN]) {
pattern.lastIndex = 0;
let match: RegExpExecArray | null;
@ -207,9 +248,9 @@ export const manageDialogueHighlight = (doc: Document, viewSettings: ViewSetting
clearDialogueHighlight(doc);
if (!isDialogueHighlightActive(viewSettings)) return;
if (!doc.body && !doc.documentElement) return;
const { entries, text } = collectEntries(doc);
const { entries, text, blocks } = collectEntries(doc);
if (entries.length === 0) return;
wrapRegions(doc, entries, findRegions(text));
wrapRegions(doc, entries, findRegions(text, blocks));
markDashBlocks(doc);
};