vomebook commited on
Commit ·
472fce5
1
Parent(s): e6e90f2
Apply saved theme before search and Reader first paint
Browse filesFiles changed (11)
- static/app.js+16-2
- static/index.html+21-4
- static/reader.html+16
- static/reader.js+4-2
- static/reader/core/reader-bindings.mjs+40-6
- static/reader/ui/reader-ui.mjs+5
- static/search/shell/presentation/view.js+2
- static/style.css+10-5
- tests/reader/browser/test_reader_accessibility_browser.py+53
- tests/reader/browser/test_reader_navigation_host.py+39
- tests/search/ui/shell_contracts.mjs+7-2
3677 unmodified lines36783679368036813682368336843685368636873688368936903691369236933694369536963697369836997 unmodified lines370737083709369436953710371137123677 unmodified lines
async function init() { cacheDOM(); const syncStoredTheme = () => { let theme; try { theme = localStorage.getItem("theme"); } catch (_) { return; } const isDark = theme !== "light"; if (STATE.isDark === isDark) return; STATE.isDark = isDark; applyTheme(); }; STATE.isDark = document.documentElement.dataset.theme !== "light"; // Storage may have changed while the deferred entry was loading. try { STATE.isDark = localStorage.getItem("theme") !== "light"; } catch (_) {} applyTheme(); window.addEventListener("storage", event => { if (event.key === "theme" || event.key === null) syncStoredTheme(); }); window.addEventListener("pageshow", event => { if (event.persisted) syncStoredTheme(); }); getSidebarScroll().install(); syncSearchInputState(); setupSearchInput();7 unmodified lines if ("scrollRestoration" in history) history.scrollRestoration = "manual"; await restoredSession; setupReaderIntentWarming(); STATE.isDark = readSearchPreference("theme") !== "light"; applyTheme(); const savedMobile = readSearchPreference("mobileMode"); if (savedMobile === "mobile") STATE.isMobile = true; else if (savedMobile === "desktop") STATE.isMobile = false;2 unmodified lines3456678910111213141516171819202122232425262711 unmodified lines394041244243445 unmodified lines505152365354555667 unmodified lines1241251261101271281291302 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><script>try { if (matchMedia("(max-width: 768px)").matches && localStorage.getItem("mobileMode") !== "desktop") document.documentElement.classList.add("mobile-boot"); } catch (_) { if (matchMedia("(max-width: 768px)").matches) document.documentElement.classList.add("mobile-boot"); }</script><meta name="theme-color" content="#1a1c1e"><script>(() => { const root = document.documentElement; root.dataset.theme = "dark"; try { if (localStorage.getItem("theme") === "light") { root.dataset.theme = "light"; document.querySelector('meta[name="theme-color"]').setAttribute("content", "#fdfbff"); } } catch (_) {} try { if (matchMedia("(max-width: 768px)").matches && localStorage.getItem("mobileMode") !== "desktop") document.documentElement.classList.add("mobile-boot"); } catch (_) { if (matchMedia("(max-width: 768px)").matches) document.documentElement.classList.add("mobile-boot"); }})();</script><style>:root { color-scheme: dark; background: #1a1c1e; }:root[data-theme="light"] { color-scheme: light; background: #fdfbff; }</style><!-- SEO:HEAD --><title>VoiceOfML Search</title><meta name="description" content="检索 VoiceOfML 公开资料的文件名、路径和格式,浏览文库目录,在线阅读或下载原始文件。">11 unmodified lines<!-- HF supplies the HTTP canonical; do not add a conflicting HTML canonical. --><!-- /SEO:HEAD --><link rel="manifest" href="/manifest.json"><meta name="theme-color" content="#1a1c1e"><meta name="mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">5 unmodified lines<script>fetch("/api/ping", { cache: "no-store" }).catch(() => {});</script><link rel="stylesheet" href="/static/style.css"></head><body class="dark"><body><a class="skip-link" href="#results-container">跳转到搜索结果</a><div id="search-announcement" class="sr-only" role="status" aria-live="polite" aria-atomic="true"></div>
67 unmodified lines </svg> </button> <button id="theme-btn" class="icon-btn" aria-label="切换主题" title="深色/浅色模式"> <svg id="theme-icon-light" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:none"> <svg id="theme-icon-light" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <circle cx="12" cy="12" r="5"/> <line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/> <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>8 unmodified lines91011121314151617181920212223242526272829308 unmodified lines content="default-src 'self'; base-uri 'self' blob:; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline' blob:; font-src 'self' blob:; img-src 'self' data: blob: https:; media-src 'self' https://voiceofml-search.hf.space https://hf-mirror.com https://huggingface.co https://*.hf.co https://*.huggingface.co https://vomebook-hitokoto.hf.space blob:; connect-src 'self' blob: https://huggingface.co https://*.hf.co https://*.huggingface.co https://voiceofml-search.hf.space https://hf-mirror.com https://vomebook-hitokoto.hf.space; frame-src 'self' blob:;" /> <title>VoiceOfML Reader</title> <meta name="theme-color" content="#111315" /> <script> (() => { let theme; try { if (parent !== window) theme = parent.document.documentElement.dataset.theme; } catch (_) {} if (theme !== "light" && theme !== "dark") { try { theme = localStorage.getItem("theme"); } catch (_) {} } document.documentElement.dataset.theme = theme === "light" ? "light" : "dark"; if (theme === "light") document.querySelector('meta[name="theme-color"]').setAttribute("content", "#f4f5f6"); })(); </script> <style> :root { color-scheme: dark; background: #111315; } :root[data-theme="light"] { color-scheme: light; background: #f4f5f6; } </style> <script> // Start source lookup before the Reader module graph loads; consume it once. (() => {1059 unmodified lines1060106110621063106410631064106510661067106810691059 unmodified lines mediaPanel = document.createElement("section");readerBindings.mountMediaPanel();// Theme, toolbar, and document navigation.let readerTheme = "dark";try { if (localStorage.getItem("theme") === "light") readerTheme = "light"; } catch (_) {}let readerTheme = document.documentElement.dataset.theme === "light" ? "light" : "dark";if (!document.documentElement.dataset.theme) { try { if (localStorage.getItem("theme") === "light") readerTheme = "light"; } catch (_) {}}const THEME_SUN_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="5"/><path d="M12 1v2m0 18v2M4.22 4.22l1.42 1.42m12.72 12.72 1.42 1.42M1 12h2m18 0h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>';const THEME_MOON_ICON =376 unmodified lines377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408383409410411412413388414415416417418419390420421422423424425426284 unmodified lines71171271368171471571671723 unmodified lines741742743711744745746713747748749750376 unmodified lines readerContext.applyPageInversion(); }
/** @param {string | null} theme @param {boolean} [resume] */ function syncReaderTheme(theme, resume = false) { const next = theme === "light" ? "light" : "dark"; if (next !== readerContext.readerTheme || (resume && document.documentElement.classList.contains("theme-transition"))) { readerContext.applyReaderTheme(next, false, false); } }
/** @param {boolean} [resume] */ function syncStoredReaderTheme(resume = false) { try { syncReaderTheme(localStorage.getItem("theme"), resume); } catch (_) {} }
function activeReaderTheme() { // The Search shell also owns the first frame of embedded Readers when // storage is unavailable or the preference changes during module loading. try { if (window.parent !== window) { const theme = window.parent.document.documentElement.dataset.theme; if (theme === "light" || theme === "dark") return theme; } } catch (_) {} try { return localStorage.getItem("theme") === "light" ? "light" : "dark"; } catch (_) { return readerContext.readerTheme; } }
function restoreReaderThemeAndBindReturn() { readerContext.readerThemeToggle.className = "theme-toggle";
readerContext.applyReaderTheme(readerContext.readerTheme, false, false); readerContext.applyReaderTheme(activeReaderTheme(), false, false);
readerContext.readerPath.addEventListener("click", readerContext.navigateReaderFolder); document.querySelector("#reader-panel-path")?.addEventListener("click", readerContext.navigateReaderFolder); let closing = false; window.addEventListener("pageshow", event => { if (event.persisted) closing = false; }); window.addEventListener("pageshow", event => { if (!event.persisted) return; closing = false; syncStoredReaderTheme(true); }); // A parked speech iframe is shown again without a document navigation. window.addEventListener("voice-reader-overlay-resume", () => { closing = false; }); window.addEventListener("voice-reader-overlay-resume", () => { closing = false; syncReaderTheme(activeReaderTheme(), true); }); /** @type {Element} */ (document.querySelector("#back")).addEventListener("click", async () => { if (closing) return; closing = true;284 unmodified lines window.parent.postMessage({ type: "voice-reader-theme", theme }, location.origin); }); window.addEventListener("storage", (event) => { if (event.key === "theme" && event.newValue) readerContext.applyReaderTheme(event.newValue, false); if (event.key === "theme" || event.key === null) syncStoredReaderTheme(); }); window.addEventListener("voice-reader-capture-progress", event => { if (!readerContext.isReaderOverlayFrame()) return;23 unmodified lines event.origin === location.origin && event.source === window.parent && event.data && event.data.type === "voice-reader-theme-state" event.data.type === "voice-reader-theme-state" && (event.data.theme === "light" || event.data.theme === "dark") ) readerContext.applyReaderTheme(event.data.theme, false); syncReaderTheme(event.data.theme); }); /** @type {HTMLButtonElement} */ (document.querySelector("#history")) .addEventListener("click", (event) =>35 unmodified lines363738394041424344454647484935 unmodified lines clearTimeout(readerContext.themeAnimationTimer); document.documentElement.classList.add("theme-transition"); void document.documentElement.offsetWidth; } else { clearTimeout(readerContext.themeAnimationTimer); document.documentElement.classList.remove("theme-transition"); readerContext.readerThemeToggle.classList.remove("is-changing"); } readerContext.readerTheme = theme === "light" ? "light" : "dark"; document.documentElement.dataset.theme = readerContext.readerTheme; document.querySelector('meta[name="theme-color"]')?.setAttribute("content", readerContext.readerTheme === "light" ? "#f4f5f6" : "#111315"); readerContext.readerThemeToggle.innerHTML = readerContext.readerTheme === "dark" ? readerContext.THEME_MOON_ICON : readerContext.THEME_SUN_ICON; if (animate) { readerContext.readerThemeToggle.classList.remove("is-changing");36 unmodified lines373839404142434436 unmodified lines /** @param {boolean} isDark */ function applyTheme(isDark) { const el = elements(); document.documentElement.setAttribute("data-theme", isDark ? "dark" : "light"); document.querySelector('meta[name="theme-color"]')?.setAttribute("content", isDark ? "#1a1c1e" : "#fdfbff"); el.themeBtn.setAttribute('aria-label', isDark ? '切换到浅色主题' : '切换到深色主题'); if (isDark) { document.body.classList.remove("light");66 unmodified lines676869707071727321 unmodified lines95969798989910010110214 unmodified lines117118119120121122123124125126161 unmodified lines288289290286291292293294290295296297298395 unmodified lines69469569669269769869970066 unmodified lines width: 100%; height: 100%; border: 0; background: #181a1d; background: var(--reader-overlay-background, #111315);}
.reader-overlay-pending { visibility: hidden; }21 unmodified lines cursor: pointer;}
body.light {:root[data-theme="light"] { --reader-overlay-background: #f4f5f6; --surface: #fdfbff; --surface-variant: #f0eff4; --surface-container: #f5f3f7;14 unmodified lines color-scheme: light;}
#theme-icon-light,:root[data-theme="light"] #theme-icon-dark { display: none; }:root[data-theme="light"] #theme-icon-light { display: inline; }
*, *::before, *::after { box-sizing: border-box; margin: 0;161 unmodified lines display: none;}
body.light .header-logo-icon-dark {:root[data-theme="light"] .header-logo-icon-dark { display: none;}
body.light .header-logo-icon-light {:root[data-theme="light"] .header-logo-icon-light { display: block;}
395 unmodified lines background: rgba(255, 255, 255, 0.04);}
body.light .left-sidebar.expanded-wide .browser-item:nth-child(even) {:root[data-theme="light"] .left-sidebar.expanded-wide .browser-item:nth-child(even) { background: rgba(0, 0, 0, 0.04);}
37 unmodified lines383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959637 unmodified lines self.page.locator('#history').press('Enter') self.page.locator('#history').press('Enter')
def test_saved_theme_colors_both_shells_before_app_and_reader_scripts(self): # Hold the main entry out of the test entirely: a post-init assertion # would miss the dark frame while modules or IndexedDB are pending. self.page.route('**/static/app.js', lambda route: route.abort()) self.page.route('**/static/reader.js', lambda route: route.abort()) search_url = self.origin + support.PREFIX + '/' index = (support.ROOT / 'static/index.html').read_text() self.page.route(search_url, lambda route: route.fulfill(content_type='text/html', body=index)) reader_url = self.origin + support.PREFIX + '/static/reader.html?ext=txt' self.page.route(self.origin + '/theme-test-setup', lambda route: route.fulfill(body='setup')) self.page.goto(self.origin + '/theme-test-setup') self.page.evaluate("localStorage.setItem('theme', 'light')") def colors(): return self.page.evaluate('''() => { const root = getComputedStyle(document.documentElement); const shell = document.querySelector('.reader-toolbar') || document.body; return [root.colorScheme, root.backgroundColor, getComputedStyle(shell).backgroundColor, document.querySelector('meta[name="theme-color"]').content]; }''') light_search = ['light', 'rgb(253, 251, 255)', 'rgb(253, 251, 255)', '#fdfbff'] light_reader = ['light', 'rgb(244, 245, 246)', 'rgb(255, 255, 255)', '#f4f5f6'] cdp = self.context.new_cdp_session(self.page) for width, agent in ((390, 'Mozilla/5.0 (Linux; Android 14) Chrome/145 Mobile'), (1280, 'Mozilla/5.0 (X11; Linux x86_64) Chrome/145')): cdp.send('Network.setUserAgentOverride', {'userAgent': agent}) self.page.set_viewport_size(dict(width=width, height=800)) self.page.goto(search_url) self.assertEqual(colors(), light_search) self.assertEqual(self.page.locator('html').evaluate("el => el.classList.contains('mobile-boot')"), width == 390) self.page.goto(reader_url) self.assertEqual(colors(), light_reader) self.page.go_back() self.assertEqual(colors(), light_search) self.page.reload() self.assertEqual(colors(), light_search) self.page.evaluate("localStorage.setItem('theme', 'dark')") self.page.reload() self.assertEqual(colors(), ['dark', 'rgb(26, 28, 30)', 'rgb(26, 28, 30)', '#1a1c1e']) self.page.goto(reader_url) self.assertEqual(colors(), ['dark', 'rgb(17, 19, 21)', 'rgb(27, 30, 33)', '#111315'])
def test_reader_history_restore_applies_theme_without_transition(self): self.open_book(open_panel=False) state = self.page.evaluate('''() => { const root = document.documentElement; localStorage.setItem('theme', 'light'); root.classList.add('theme-transition'); window.dispatchEvent(new PageTransitionEvent('pageshow', {persisted: true})); return [root.dataset.theme, root.classList.contains('theme-transition'), document.querySelector('meta[name="theme-color"]').content, localStorage.getItem('theme')]; }''') self.assertEqual(state, ['light', False, '#f4f5f6', 'light'])
def test_compact_number_editors_hide_default_outline_only(self): self.page.set_viewport_size({'width': 390, 'height': 844}) # Use the existing offline PDF engine and real toolbar controls.26 unmodified lines272829303132333435363738394041424344454647484950515253545556727 unmodified lines78478578678778878979079179279379479579679779879980080180280380480580626 unmodified lines self.assertEqual(self.fixture.errors, []) self.fixture.tearDown()
def test_search_startup_uses_preference_changed_while_entry_is_loading(self): pending = [] self.page.route('**/static/app.js', lambda route: pending.append(route)) self.page.reload(wait_until='commit') self.page.wait_for_function("document.documentElement.dataset.theme === 'dark'") other = self.fixture.context.new_page() other.route(self.fixture.origin + '/theme-storage-test', lambda route: route.fulfill(body='test')) other.goto(self.fixture.origin + '/theme-storage-test') other.evaluate("localStorage.setItem('theme', 'light')") other.close() self.assertEqual(len(pending), 1) pending.pop().continue_() self.page.wait_for_function("typeof STATE !== 'undefined' && !STATE.isDark && document.documentElement.dataset.theme === 'light'")
def test_search_history_restore_resyncs_theme_without_ripple(self): restored = self.page.evaluate('''() => { localStorage.setItem('theme', 'light'); window.dispatchEvent(new PageTransitionEvent('pageshow', {persisted: true})); return [STATE.isDark, getComputedStyle(document.documentElement).colorScheme, document.querySelector('meta[name="theme-color"]').content, !!document.querySelector('.theme-ripple')]; }''') self.assertEqual(restored, [False, 'light', '#fdfbff', False])
def test_bundled_shell_starts_without_separate_dependency_scripts(self): root = Path(__file__).resolve().parents[3] shell = subprocess.check_output(['node', '--input-type=module', '-e', '''727 unmodified lines self.assertEqual(self.page.url, search_url) self.assertTrue(self.page.evaluate('!readerHost.overlay && readerNavigation.backgroundReader === __speechFrame')) if reopen: # Model a parked Reader that missed a preference update while # hidden. Reopen must sync theme even before a frame is painted. self.page.evaluate('''() => { STATE.isDark = false; applyTheme(); __speechDocument.documentElement.classList.add('theme-transition'); __speechFrame.contentWindow.addEventListener('voice-reader-overlay-resume', () => { const root = __speechDocument.documentElement; window.__resumedTheme = [root.dataset.theme, root.classList.contains('theme-transition'), document.activeElement === __speechFrame]; }, {once: true}); }''') bar.get_by_role('button', name='返回阅读').click() self.assertTrue(self.page.evaluate('readerHost.overlay === __speechFrame && __speechFrame.contentDocument === __speechDocument')) self.assertEqual(self.page.evaluate('__resumedTheme'), ['light', False, False]) self.assertEqual(self.page.locator('.reader-overlay').evaluate('el => getComputedStyle(el).backgroundColor'), 'rgb(244, 245, 246)') bar.get_by_role('button', name='停止朗读并关闭阅读器').click() self.assertFalse(self.page.evaluate('__speechFrame.isConnected'))
41 unmodified lines42434445454647484914 unmodified lines646566666768697027 unmodified lines98991001011021031041058 unmodified lines11411511611711811912012141 unmodified lines const leftControl = element('leftControl', DOM.leftSidebar), rightControl = element('rightControl', DOM.rightSidebar); DOM.leftSidebar.controls = [leftControl]; DOM.rightSidebar.controls = [rightControl]; document.body = element('body'); document.documentElement = element('html'); document.querySelector = selector => { assert.equal(selector, '#main-content'); return main; }; const themeColor = element('theme-color'); document.querySelector = selector => selector === 'meta[name="theme-color"]' ? themeColor : main; document.createElement = () => element('ripple'); const c = vm.createContext({shell: null, DOM, document, STATE: {isDark: true, isMobile: false, leftSidebarOpen: true, rightSidebarOpen: false},14 unmodified lines const single = app.match(new RegExp('^function ' + name + '\\([^\\n]*\\}\\s*$', 'm')); assert.ok(single || match, name); vm.runInContext((single || match)[0], c); } return {c, events, nodes, frames, messages, document, DOM, main, mainControl, leftControl, rightControl, element}; return {c, events, nodes, frames, messages, document, DOM, main, mainControl, leftControl, rightControl, element, themeColor};}
test('shell modules are registered once in source, bundle, offline, resources and strict projects', async () => {27 unmodified lines f.c.toggleTheme(); assert.equal(f.c.STATE.isDark, false); assert.equal(f.document.body.classes.has('light'), true); assert.equal(f.document.documentElement.attributes['data-theme'], 'light'); assert.equal(f.themeColor.attributes.content, '#fdfbff'); assert.equal(f.DOM.themeIconDark.style.display, 'none'); assert.deepEqual(f.messages, [[{type: 'voice-reader-theme-state', theme: 'light'}, 'https://shell.test']]); assert.deepEqual(f.events.slice(-3), [['reader', 'light'], ['preference', 'theme', 'light'], ['listen', 'animationend']]);8 unmodified lines f.c.toggleTheme(); assert.equal(f.c.STATE.isDark, true); assert.equal(f.nodes[1].style.background, '#1a1c1e'); assert.equal(f.document.body.classes.has('light'), false); assert.equal(f.document.documentElement.attributes['data-theme'], 'dark'); assert.equal(f.themeColor.attributes.content, '#1a1c1e');});
test('mobile defaults apply before header, selection, scheduled scroll and preference write', () => {static/app.js+16-2
static/index.html+21-4
static/reader.html+16
static/reader.js+4-2
static/reader/core/reader-bindings.mjs+40-6
static/reader/ui/reader-ui.mjs+5
static/search/shell/presentation/view.js+2
static/style.css+10-5
tests/reader/browser/test_reader_accessibility_browser.py+53
tests/reader/browser/test_reader_navigation_host.py+39
tests/search/ui/shell_contracts.mjs+7-2