"""Focused browser checks for reader CSS, independent of format-engine suites."""
import io
import os
import unittest
import urllib.parse
from PIL import Image
from tests.performance.test_reader_performance import STORE_SCRIPT, PlaywrightError, static_server, sync_playwright
from tests.performance import test_reader_performance as support
from tests.support.reader_native_fixture import install as install_native_djvu
@unittest.skipIf(sync_playwright is None, "install requirements-test.txt for reader style tests")
class ReaderStyleTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.server = static_server()
cls.origin = cls.server.__enter__()
cls.addClassCleanup(cls.server.__exit__, None, None, None)
cls.playwright = sync_playwright().start()
cls.addClassCleanup(cls.playwright.stop)
try:
cls.browser = getattr(cls.playwright, os.environ.get("READER_STYLE_BROWSER", "chromium")).launch(headless=True)
except PlaywrightError as error:
raise unittest.SkipTest(str(error))
cls.addClassCleanup(cls.browser.close)
def setUp(self):
context = self.browser.new_context(viewport={"width": 1440, "height": 900})
self.addCleanup(context.close)
self.page = context.new_page()
self.page.add_init_script("localStorage.setItem('theme', 'dark')")
self.page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(
content_type="text/javascript", body=STORE_SCRIPT
))
self.page.route("**/api/reader-content**", lambda route: route.fulfill(
content_type="text/plain", body="Reader style fixture\n" * 80
))
source = urllib.parse.quote(
"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/style.txt", safe=""
)
self.page.goto(
f"{self.origin}/static/reader.html?url={source}&ext=txt&title=Style&path=Test",
wait_until="domcontentloaded",
)
self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
def settle(self):
self.page.wait_for_function("""() =>
!document.documentElement.classList.contains('theme-transition') &&
!document.getAnimations().some(animation => animation.playState === 'running')
""")
def test_default_paper_follows_theme_and_mobile_prose_scales_with_zoom(self):
viewport = self.page.locator('#viewport')
text = self.page.locator('.reader-text').first
self.assertEqual(text.evaluate('e=>getComputedStyle(e).fontSize'), '17px')
self.page.set_viewport_size({'width':390,'height':740})
self.assertEqual(text.evaluate('e=>getComputedStyle(e).fontSize'), '14px')
self.page.locator('#zoom').fill('150')
self.page.locator('#zoom').dispatch_event('change')
self.assertEqual(text.evaluate('e=>getComputedStyle(e).fontSize'), '21px')
dark = viewport.evaluate('e=>getComputedStyle(e).backgroundColor')
self.assertEqual(dark, 'rgb(32, 34, 36)')
self.assertEqual(viewport.evaluate('e=>getComputedStyle(e).backgroundImage'), 'none')
self.assert_contrast('.reader-text')
self.page.locator('#history').click()
self.page.locator('#theme-toggle').click()
self.settle()
light = viewport.evaluate('e=>getComputedStyle(e).backgroundColor')
self.assertEqual(light, 'rgb(247, 243, 235)')
self.assertEqual(viewport.evaluate('e=>getComputedStyle(e).backgroundImage'), 'none')
self.assert_contrast('.reader-text')
for media in ({'contrast':'more'}, {'contrast':'no-preference','forced_colors':'active'}):
self.page.emulate_media(**media)
self.assertNotEqual(viewport.evaluate('e=>getComputedStyle(e).backgroundColor'), light)
self.page.emulate_media(contrast='no-preference', forced_colors='none')
for mode, markup, surface in (
('markdown','
Chapter text
""" manifest = {"version": 1, "kind": "epub-chapters", "chapters": [ {"index": 1, "path": "chapters/chapter-0001.xhtml", "bytes": len(xhtml.encode("utf-8"))} ]} self.page.route("**/api/reader-bucket-resource**", lambda route: route.fulfill(json=manifest) if "chapter-manifest.json" in route.request.url else route.fulfill( content_type="application/xhtml+xml", body=xhtml, headers={"Access-Control-Allow-Origin": "*"})) params = urllib.parse.urlencode(dict(url=source, ext="epub-chapters", title="Theme")) self.page.goto(f"{self.origin}/static/reader.html?{params}") self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'") chapter = self.page.locator('#content[data-mode="epub-chapters"] .reader-epub-chapter') text = chapter.locator("#chapter-text") svg = chapter.locator("svg") for node in (chapter, text, svg): node.wait_for() initial = [node.bounding_box() for node in (chapter, text, svg)] for step, theme in enumerate(("dark", "light", "dark")): with self.subTest(step=step, theme=theme): if step: self.page.locator("#history").click() self.page.locator("#theme-toggle").click() self.page.locator("#history-close").click() self.page.locator("#history-panel").wait_for(state="hidden") self.settle() self.assertEqual(self.page.locator("html").get_attribute("data-theme"), theme) colors = text.evaluate("e => [getComputedStyle(e).color, getComputedStyle(e).backgroundColor]") self.assertEqual(colors, ["rgb(236, 239, 241)", "rgba(0, 0, 0, 0)"] if theme == "dark" else ["rgb(0, 0, 0)", "rgb(255, 255, 255)"]) self.assertEqual(svg.locator("rect").evaluate("e => getComputedStyle(e).fill"), "rgb(255, 0, 0)") self.assertEqual(svg.evaluate("e => getComputedStyle(e).filter"), "none") self.assertEqual([node.bounding_box() for node in (chapter, text, svg)], initial) def test_numeric_controls_keep_keyboard_focus_without_default_outline_in_both_themes(self): self.page.locator(".page-controls").evaluate("element => element.hidden = false") for theme in ("dark", "light"): self.page.locator("html").evaluate("(element, theme) => element.dataset.theme = theme", theme) self.page.keyboard.press("Tab") for selector in ("#page-number", "#zoom"): control = self.page.locator(selector) control.focus() self.assertEqual(control.evaluate("""element => [ element.matches(':focus-visible'), getComputedStyle(element).outlineStyle, getComputedStyle(element.closest('.compact-input')).outlineStyle ]"""), [True, "none", "none"]) def test_short_dialog_scrolls_to_actions_and_retains_editor_grid(self): self.page.set_viewport_size({"width": 390, "height": 240}) self.page.locator("#bookmark-ribbon").click() dialog = self.page.locator("#bookmark-popover") self.page.locator("#bookmark-excerpt-input").evaluate("element => element.style.height = '500px'") metrics = dialog.evaluate("""element => ({ bottom: element.getBoundingClientRect().bottom, overflow: getComputedStyle(element).overflowY, scrollable: element.scrollHeight > element.clientHeight, editor: getComputedStyle(element.querySelector('.bookmark-edit-fields')).display })""") self.assertLessEqual(metrics["bottom"], 230) self.assertEqual(metrics["overflow"], "auto") self.assertTrue(metrics["scrollable"]) self.assertEqual(metrics["editor"], "grid") cancel = self.page.locator("#bookmark-cancel") cancel.scroll_into_view_if_needed() rect = cancel.bounding_box() self.assertGreaterEqual(rect["y"], 78) self.assertLessEqual(rect["y"] + rect["height"], 230) cancel.click() self.assertTrue(dialog.is_hidden()) def test_video_follows_toolbar_across_breakpoint_and_resize(self): for width, height in ((390, 844), (390, 360), (600, 500), (601, 500), (1440, 900)): with self.subTest(width=width, height=height): self.page.set_viewport_size({"width": width, "height": height}) for mode in ("video",): metrics = self.page.locator("#content").evaluate("""(content, mode) => { content.dataset.mode = mode; content.innerHTML = mode === 'video' ? '' : ''; const toolbar = document.querySelector('.reader-toolbar').getBoundingClientRect(); const style = getComputedStyle(content); return {toolbar: toolbar.height, height: parseFloat(style.height), minHeight: parseFloat(style.minHeight), padding: style.padding, video: content.firstChild?.getBoundingClientRect().height}; }""", mode) expected_toolbar = 36 if width <= 600 else 44 self.assertEqual(metrics["toolbar"], expected_toolbar) self.assertAlmostEqual(metrics["height"], height - expected_toolbar, delta=1) self.assertEqual(metrics["padding"], "0px") self.assertAlmostEqual(metrics["video"], height - expected_toolbar, delta=1) def test_mobile_folder_action_and_title_follow_breakpoint(self): self.page.emulate_media(reduced_motion='reduce') for width, height in ((320, 568), (390, 844), (600, 500), (601, 500)): with self.subTest(width=width, height=height): self.page.set_viewport_size({'width': width, 'height': height}) self.assertEqual(self.page.locator('.reader-toolbar').bounding_box()['height'], 36 if width <= 600 else 44) self.assertEqual(self.page.locator('#reader-path').is_visible(), width > 600) self.assertEqual(self.page.locator('#title').is_visible(), width > 600) self.page.locator('#history').click() self.page.wait_for_function("()=>document.querySelector('#history').getAttribute('aria-expanded') === 'true'") info=self.page.locator('#reader-panel-location') self.assertEqual(self.page.locator('#reader-location-toggle').count(), 0) self.assertEqual(info.is_visible(), width <= 600) if width <= 600: header=self.page.locator('#history-panel > header') self.page.evaluate("()=>document.querySelector('#page-invert-toggle').hidden=false") for search_open in (False,True): if search_open: self.page.locator('#full-search-toggle').click() buttons=header.locator('button:visible') boxes=[buttons.nth(i).bounding_box() for i in range(buttons.count())] self.assertTrue(all(boxes[i]['x']+boxes[i]['width']<=boxes[i+1]['x']+.5 for i in range(len(boxes)-1)),boxes) self.assertLessEqual(boxes[-1]['x']+boxes[-1]['width'],width) self.page.locator('#history-close').click() self.page.wait_for_function("()=>document.querySelector('#history').getAttribute('aria-expanded') === 'false'") self.assertTrue(info.is_hidden()) self.page.evaluate("()=>document.querySelector('#page-invert-toggle').hidden=true") def test_mobile_title_and_controls_fit_all_formats(self): self.page.emulate_media(reduced_motion='reduce') actions = self.page.locator('.reader-actions') # The speech button loads asynchronously, even after the Reader is ready. actions.locator('[data-speech-toggle]').wait_for() self.page.evaluate("""() => { document.querySelector('#title').textContent = '标题很长的书名'.repeat(15); document.querySelector('#page-total').textContent = '/ 12345'; const ocr = document.createElement('a'); ocr.id = 'ocr'; ocr.className = 'text-button'; ocr.textContent = 'OCR'; ocr.href = '#ocr-fixture'; document.querySelector('.reader-actions [data-speech-toggle]').after(ocr); }""") cases = [(width, pagination, zoom) for width in (320, 390, 600) for pagination, zoom in ((False, False), (False, True), (True, True))] # At 280px, even the fixed-width controls alone are wider than the strip. for width, pagination, zoom in [*cases, (280, True, True)]: with self.subTest(width=width, pagination=pagination, zoom=zoom): self.page.set_viewport_size({'width': width, 'height': 700}) self.page.evaluate('''([pagination, zoom]) => { document.querySelector('.page-controls').hidden = !pagination; document.querySelector('.zoom-controls').hidden = !zoom; document.querySelector('.reader-actions').scrollLeft = 0; }''', [pagination, zoom]) layout = actions.evaluate('''actions => { const rect = node => node.getBoundingClientRect().toJSON(); const controls = [...actions.querySelectorAll('button, input, a')] .filter(node => node.getClientRects().length) .map(node => ({selector: node.id ? '#' + node.id : '[data-speech-toggle]', ...rect(node)})); return {controls, toolbar: rect(actions.closest('header')), strip: rect(actions), back: rect(document.querySelector('#back')), menu: rect(document.querySelector('#history')), scroll: actions.scrollWidth > actions.clientWidth}; }''') toolbar, strip, back, menu = (layout[key] for key in ('toolbar', 'strip', 'back', 'menu')) self.assertEqual(toolbar['height'], 36) self.assertTrue(self.page.locator('#title').is_hidden()) self.assertGreaterEqual(back['left'], toolbar['left']) self.assertGreaterEqual(strip['left'], back['right']) self.assertLessEqual(strip['right'], menu['left']) self.assertLessEqual(menu['right'], toolbar['right']) expected = ['[data-speech-toggle]', '#ocr'] if pagination: expected += ['#page-prev', '#page-number', '#page-next'] if zoom: expected += ['#zoom-out', '#zoom', '#zoom-in'] expected += ['#download'] controls = layout['controls'] self.assertEqual([box['selector'] for box in controls], expected) for box in (back, strip, *controls, menu): self.assertGreaterEqual(box['top'], toolbar['top'], box) self.assertLessEqual(box['bottom'], toolbar['bottom'], box) for previous, following in zip(controls, controls[1:]): self.assertLessEqual(previous['right'], following['left'] + 0.5, (previous, following)) if width == 280: self.assertTrue(layout['scroll'], layout) if not layout['scroll']: for box in controls: self.assertGreaterEqual(box['left'], strip['left'], box) self.assertLessEqual(box['right'], strip['right'], box) # Tab must reach every control, including those clipped by the scrolling strip. self.page.locator('#back').focus() self.page.keyboard.press('Tab') # Some browsers give the scroll container its own tab stop. if actions.evaluate('node => node === document.activeElement'): self.page.keyboard.press('Tab') for selector in expected: focus = actions.locator(selector).evaluate('''node => { const box = node.getBoundingClientRect(); const strip = node.closest('.reader-actions').getBoundingClientRect(); return {focused: node.matches(':focus-visible'), outline: getComputedStyle(node).outlineStyle, left: box.left - strip.left, right: strip.right - box.right}; }''') self.assertTrue(focus['focused'], (selector, focus)) outline = 'none' if selector in ('#page-number', '#zoom') else 'solid' self.assertEqual(focus['outline'], outline, (selector, focus)) self.assertGreaterEqual(focus['left'], -0.5, (selector, focus)) self.assertGreaterEqual(focus['right'], -0.5, (selector, focus)) self.page.keyboard.press('Tab') if layout['scroll']: self.assertGreater(actions.evaluate('node => node.scrollLeft'), 0) self.assertTrue(self.page.locator('#history').evaluate("node => node.matches(':focus-visible')")) self.assertEqual(self.page.locator('#back').bounding_box()['x'], back['left']) self.assertEqual(self.page.locator('#history').bounding_box()['x'], menu['left']) def test_mobile_overflowing_toolbar_supports_touch_swipe(self): context=self.browser.new_context(viewport={'width':280,'height':700},is_mobile=True,has_touch=True) try: page=context.new_page() page.route('**/api/reader-content**',lambda route:route.fulfill(content_type='text/plain',body='Readable text')) source=urllib.parse.quote('https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/touch.txt',safe='') page.goto(f'{self.origin}/static/reader.html?url={source}&ext=txt&title=Touch') page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'") page.evaluate('''()=>{document.querySelector('.page-controls').hidden=false; const ocr=document.createElement('a');ocr.className='text-button';ocr.textContent='OCR'; document.querySelector('.reader-actions').prepend(ocr)}''') actions=page.locator('.reader-actions') self.assertGreater(actions.evaluate('n=>n.scrollWidth'),actions.evaluate('n=>n.clientWidth')) box=actions.bounding_box();session=context.new_cdp_session(page) x,y=box['x']+box['width']-15,box['y']+box['height']/2 session.send('Input.dispatchTouchEvent',{'type':'touchStart','touchPoints':[{'x':x,'y':y}]}) for delta in (25,50,75,100): session.send('Input.dispatchTouchEvent',{'type':'touchMove','touchPoints':[{'x':x-delta,'y':y}]}) page.wait_for_timeout(25) session.send('Input.dispatchTouchEvent',{'type':'touchEnd','touchPoints':[]}) page.wait_for_function("()=>document.querySelector('.reader-actions').scrollLeft>0") self.assertEqual(page.locator('.reader-toolbar').bounding_box()['height'],36) finally: context.close() def test_mobile_folder_action_has_contrast_and_stays_out_of_header(self): self.page.set_viewport_size({'width': 320, 'height': 568}) self.page.emulate_media(reduced_motion='reduce') # Exceed the panel width even with a narrow CI fallback font. self.page.evaluate("()=>document.querySelector('.reader-panel-folder').textContent='所在目录:Test/'+ '一个非常长的目录/子目录/'.repeat(8)+'文件所在位置'") self.page.locator('#history').click() action = self.page.locator('#reader-panel-path') action.wait_for(state='visible') for theme in ('dark', 'light'): with self.subTest(theme=theme): self.page.evaluate('theme=>document.documentElement.dataset.theme=theme', theme) self.assert_contrast('#reader-panel-path') action.hover() self.assert_contrast('#reader-panel-path') geometry = action.evaluate('''node=>{ const a=node.getBoundingClientRect(),h=document.querySelector('#history-panel > header').getBoundingClientRect(); const tabs=document.querySelector('.reader-panel-tabs').getBoundingClientRect(); const text=node.querySelector('.reader-panel-folder'); return {belowHeader:a.top>=h.bottom,aboveTabs:a.bottom<=tabs.top,ellipsized:text.scrollWidth>text.clientWidth}; }''') self.assertTrue(all(geometry.values()), geometry) def test_mobile_file_info_works_without_a_folder_target(self): self.page.set_viewport_size({'width':320,'height':568}) self.page.emulate_media(reduced_motion='reduce') self.page.locator('#history').click() self.assertEqual(self.page.get_by_role('button',name='文件信息',exact=True).count(), 0) self.assertTrue(self.page.locator('#reader-panel-path').is_disabled()) self.assertTrue(self.page.locator('#title').is_hidden()) self.assertTrue(self.page.locator('#reader-panel-location').is_visible()) self.page.locator('#history-tab').click() self.assertTrue(self.page.locator('#reader-panel-location').is_visible()) self.page.locator('#history-close').click() self.page.wait_for_function("()=>document.querySelector('#history-panel').hidden") self.assertTrue(self.page.locator('#reader-panel-location').is_hidden()) self.page.locator('#history').click() self.assertTrue(self.page.locator('#reader-panel-location').is_visible()) def test_mobile_panel_is_compact_and_folder_scrolls_with_directory(self): self.page.emulate_media(reduced_motion='reduce') self.page.evaluate('''()=>{ document.querySelector('.reader-panel-folder').textContent='所在目录:Test/docs'; document.querySelector('#toc-list').innerHTML=Array.from({length:40},(_,i)=> `