fix(reader): keep the CJK widow/orphan lift alive under Use Book Layout (#6711)

* fix(reader): keep the CJK widow/orphan lift alive under Use Book Layout

Use Book Layout skips the paragraph layout chunk wholesale, taking its
`:lang(zh), :lang(ja), :lang(ko) { widows: 1; orphans: 1 }` lift with
it. A CJK book wearing the placeholder `en` that conversion tools stamp
on the root tag (#6672) then falls back to the UA default of 2, and the
page-bottom gap that lift closes comes back in this mode.

Ship a zero-specificity `:where()` twin of the lift in an
always-present chunk: inert wherever the paragraph chunk is present,
and under Use Book Layout still subordinate to any widows/orphans the
book declares, so that mode's contract that the book's own formatting
wins stays intact.

* fix(reader): scope the CJK widow/orphan fallback to the section root

A direct declaration beats an inherited value at any specificity, so the
element-wide `:where(:lang(...))` fallback still stomped widows/orphans
a CJK book declared on html or body and expected its paragraphs to
inherit — the very declarations Use Book Layout exists to honor. Take
the fallback on `html:lang()` instead: the 1s flow down to every
paragraph the book says nothing about, and a declaration at any
ancestor, or on the paragraph itself, wins. The inheritance semantics
are asserted in a real engine (cjk-widows-fallback.browser.test.ts).
This commit is contained in:
k6G52m4Dz75W 2026-10-13 12:56:45 +08:00 • committed by GitHub
parent 27b7d7379b
commit 2a1bef1257
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 190 additions and 2 deletions

View file

@ -0,0 +1,132 @@
import { describe, test, expect, afterEach } from 'vitest';
import { getStyles, ThemeCode } from '@/utils/style';
import { ViewSettings } from '@/types/book';
import {
DEFAULT_BOOK_FONT,
DEFAULT_BOOK_LAYOUT,
DEFAULT_BOOK_LANGUAGE,
DEFAULT_BOOK_STYLE,
DEFAULT_VIEW_CONFIG,
DEFAULT_TTS_CONFIG,
DEFAULT_TRANSLATOR_CONFIG,
DEFAULT_ANNOTATOR_CONFIG,
DEFAULT_SCREEN_CONFIG,
} from '@/services/constants';
// The Use Book Layout root fallback for CJK lives on `html:lang()` at zero
// specificity so the UA default of 2 only applies when the book says nothing
// at all. Cascade mechanics decide every case here: a direct declaration
// beats an inherited value at any specificity (so the fallback must NOT sit
// on the paragraphs themselves, or it would stomp book declarations made on
// html/body and expected to inherit), while a zero-specificity root
// declaration loses to anything the book declares anywhere. These assert the
// resolved widows/orphans in a real engine rather than emitted selector text.
function makeViewSettings(overrides: Partial<ViewSettings> = {}): ViewSettings {
return {
...DEFAULT_BOOK_FONT,
...DEFAULT_BOOK_LAYOUT,
...DEFAULT_BOOK_LANGUAGE,
...DEFAULT_BOOK_STYLE,
...DEFAULT_VIEW_CONFIG,
...DEFAULT_TTS_CONFIG,
...DEFAULT_TRANSLATOR_CONFIG,
...DEFAULT_ANNOTATOR_CONFIG,
...DEFAULT_SCREEN_CONFIG,
...overrides,
} as ViewSettings;
}
const themeCode: ThemeCode = {
bg: '#ffffff',
fg: '#000000',
primary: '#3366cc',
isDarkMode: false,
palette: {
'base-100': '#ffffff',
'base-200': '#f0f0f0',
'base-300': '#e0e0e0',
'base-content': '#000000',
neutral: '#808080',
'neutral-content': '#ffffff',
primary: '#3366cc',
secondary: '#6699cc',
accent: '#33cc99',
},
} as ThemeCode;
const iframes: HTMLIFrameElement[] = [];
// Mirrors the paginator's injection order — the book's author CSS already in
// <head>, the reader's generated stylesheet appended after it — and the
// language transformer's output, which leaves `lang` on the section root
// (#6672 rewrites a mislabeled `en` to the detected CJK there).
const renderSection = (bookLang: string, bookCss: string, settings: Partial<ViewSettings>) => {
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframes.push(iframe);
const doc = iframe.contentDocument!;
doc.documentElement.setAttribute('lang', bookLang);
const bookStyle = doc.createElement('style');
bookStyle.textContent = bookCss;
doc.head.appendChild(bookStyle);
const readerStyle = doc.createElement('style');
readerStyle.textContent = getStyles(makeViewSettings(settings), themeCode);
doc.head.appendChild(readerStyle);
doc.body.innerHTML = `<p>第一段。</p><p>第二段。</p>`;
return { doc, win: iframe.contentWindow! };
};
const lineBreakOf = (bookLang: string, bookCss: string, settings: Partial<ViewSettings>) => {
const { doc, win } = renderSection(bookLang, bookCss, settings);
const cs = win.getComputedStyle(doc.querySelector('p') as HTMLElement);
return `${cs.widows}/${cs.orphans}`;
};
afterEach(() => {
while (iframes.length) iframes.pop()!.remove();
});
describe('CJK widow/orphan root fallback vs Use Book Layout', () => {
test('fills the UA default of 2 with 1 when the book declares nothing', () => {
expect(lineBreakOf('zh', '', { useBookLayout: true })).toBe('1/1');
});
test('preserves a book declaration inherited from html', () => {
expect(lineBreakOf('zh', 'html { widows: 3; orphans: 3; }', { useBookLayout: true })).toBe(
'3/3',
);
});
test('preserves a book declaration on body over the root fallback', () => {
// html gets the fallback's 1, but the book's direct body declaration wins
// on body and the paragraphs inherit from it.
expect(lineBreakOf('zh', 'body { widows: 3; orphans: 3; }', { useBookLayout: true })).toBe(
'3/3',
);
});
test('preserves a book declaration on the paragraph itself', () => {
expect(lineBreakOf('zh', 'p { widows: 3; orphans: 3; }', { useBookLayout: true })).toBe('3/3');
});
test('preserves a book declaration on an intermediate container', () => {
const { doc, win } = renderSection('zh', 'div.chapter { widows: 3; orphans: 3; }', {
useBookLayout: true,
});
doc.body.innerHTML = `<div class="chapter"><p>第一段。</p></div><p class="loose">第二段。</p>`;
const inside = win.getComputedStyle(doc.querySelector('.chapter p') as HTMLElement);
const outside = win.getComputedStyle(doc.querySelector('p.loose') as HTMLElement);
expect(`${inside.widows}/${inside.orphans}`).toBe('3/3');
expect(`${outside.widows}/${outside.orphans}`).toBe('1/1');
});
test('does not touch non-CJK books', () => {
expect(lineBreakOf('en', '', { useBookLayout: true })).toBe('2/2');
});
test('stays inert in default mode where the chunk lift answers directly', () => {
expect(lineBreakOf('zh', '', { useBookLayout: false })).toBe('1/1');
expect(lineBreakOf('zh', 'p { widows: 3; orphans: 3; }', { useBookLayout: false })).toBe('1/1');
});
});

View file

@ -478,6 +478,42 @@ describe('getLayoutStyles branches (via getStyles)', () => {
});
});
// ---------------------------------------------------------------------------
// CJK widow/orphan lift under Use Book Layout
// ---------------------------------------------------------------------------
// The paragraph chunk lifts widows/orphans to 1 for CJK via `:lang(zh)…`, but
// Use Book Layout skips that chunk wholesale and takes the lift with it — a
// CJK book mislabeled `en` (#6672) then falls back to the UA default of 2 and
// the page-bottom gap returns. A zero-specificity root fallback ships in
// every mode: inert where the chunk is present, and scoped to `html:lang()`
// so book-declared values on html/body reach the paragraphs by inheritance
// instead of being stomped by a direct declaration (which beats any inherited
// value regardless of specificity).
describe('CJK widow/orphan lift (via getStyles)', () => {
const theme = makeThemeCode();
const whereRule = (css: string) =>
css.match(/:where\(html:lang\(zh\), html:lang\(ja\), html:lang\(ko\)\)\s*\{([^}]*)\}/)?.[1] ??
'';
it('ships the zero-specificity fallback even when Use Book Layout skips the paragraph chunk', () => {
const css = getStyles(makeViewSettings({ useBookLayout: true }), theme);
// the chunk's own class-strength lift is gone…
expect(css).not.toMatch(/(^|\n)\s*:lang\(zh\), :lang\(ja\), :lang\(ko\)\s*\{/);
// …but the fallback itself survives at zero specificity, on the roots only
const rule = whereRule(css);
expect(rule).toContain('widows: 1');
expect(rule).toContain('orphans: 1');
});
it('keeps the chunk lift and the zero-specificity fallback when Use Book Layout is off', () => {
const css = getStyles(makeViewSettings({ useBookLayout: false }), theme);
expect(css).toMatch(/(^|\n)\s*:lang\(zh\), :lang\(ja\), :lang\(ko\)\s*\{/);
const rule = whereRule(css);
expect(rule).toContain('widows: 1');
expect(rule).toContain('orphans: 1');
});
});
// ---------------------------------------------------------------------------
// getColorStyles branches
// ---------------------------------------------------------------------------

View file

@ -667,6 +667,8 @@ const getPageLayoutStyles = (
// Paragraph-scoped CSS controlled by the Paragraph section of the Layout
// panel. Gated by BookStyle.useBookLayout: when true, this chunk is skipped
// and the book's own paragraph formatting takes over.
const CJK_LANGS = ['zh', 'ja', 'ko'];
const CJK_LANG_SELECTOR = CJK_LANGS.map((lang) => `:lang(${lang})`).join(', ');
const getParagraphLayoutStyles = (
overrideLayout: boolean,
paragraphMargin: number,
@ -785,7 +787,7 @@ const getParagraphLayoutStyles = (
display: flow-root;
}
:lang(zh), :lang(ja), :lang(ko) {
${CJK_LANG_SELECTOR} {
widows: 1;
orphans: 1;
}
@ -809,6 +811,23 @@ const getParagraphLayoutStyles = (
}
`;
// Zero-specificity fallback for the paragraph chunk's CJK widow/orphan lift
// above. Use Book Layout skips that chunk wholesale, taking the lift with it,
// so a CJK book wearing the placeholder `en` its conversion tool stamped
// (#6672) falls back to the UA default of 2 and the page-bottom gap the lift
// closes comes back. It is scoped to the section root on purpose: a direct
// declaration beats an inherited value at any specificity, so an element-wide
// fallback would stomp widows/orphans the book declares on html or body and
// expects its paragraphs to inherit. From the root the 1s flow to every
// paragraph the book says nothing about, while a declaration at any ancestor
// — or on the paragraph itself — still wins.
const getCJKLineFlowStyles = () => `
:where(${CJK_LANGS.map((lang) => `html:lang(${lang})`).join(', ')}) {
widows: 1;
orphans: 1;
}
`;
export const getFootnoteStyles = () => `
.duokan-footnote-content,
.duokan-footnote-item {
@ -1146,6 +1165,7 @@ export const getStyles = (
const translationStyles = getTranslationStyles(viewSettings);
const warichuStyles = getWarichuStyles();
const rubyStyles = getRubyStyles(viewSettings);
const cjkLineFlowStyles = getCJKLineFlowStyles();
const dialogueStyles = isDialogueHighlightActive(viewSettings)
? getDialogueHighlightStyles(viewSettings, themeCode)
: '';
@ -1156,7 +1176,7 @@ export const getStyles = (
// the footnote aside's border show as a stray horizontal line (#4438). Keep it
// ahead of the inlined custom `@font-face` rules.
const epubNamespace = `@namespace epub "http://www.idpf.org/2007/ops";`;
return `${epubNamespace}\n${customFontFaces}\n${pageLayoutStyles}\n${paragraphLayoutStyles}\n${fontStyles}\n${colorStyles}\n${dialogueStyles}\n${translationStyles}\n${warichuStyles}\n${rubyStyles}\n${userStylesheet}`;
return `${epubNamespace}\n${customFontFaces}\n${pageLayoutStyles}\n${paragraphLayoutStyles}\n${cjkLineFlowStyles}\n${fontStyles}\n${colorStyles}\n${dialogueStyles}\n${translationStyles}\n${warichuStyles}\n${rubyStyles}\n${userStylesheet}`;
};
// Build a CSS chunk of `@font-face` rules for the given user custom