vomebook commited on
Commit ·
c0f9fe7
1
Parent(s): cf9e90b
Update only the rows affected by Reader TOC current marking
Browse filesFiles changed (2)
160 unmodified lines16116216316416516616716816917017111 unmodified lines18318418518618718818931 unmodified lines221222223224225226227147 unmodified lines37537637737837938038138215 unmodified lines398399400401402403404405406407408409410411412413414415416417418419160 unmodified lineslink.className = "panel-item-main";link.textContent = entry.label;link.title = entry.label;if (entry.group) {row.classList.add("toc-group");link.setAttribute("role", "heading");link.setAttribute("aria-level", String(Math.min(6, (entry.depth || 0) + 1)));row.appendChild(link);return row;}link.tabIndex = 0;11 unmodified linesactivate();}});row.appendChild(link);return row;}31 unmodified linesif (!row) {row = readerContext.createTocRow(state.entries[index], index);row.classList.add("toc-virtual-row");if (state.query) readerContext.highlightPanelItem(row, state.query);cache.rows.set(index, row);}const top = `${position * readerContext.TOC_VIRTUAL_ROW_HEIGHT}px`;147 unmodified linespageLookupEntries = entries;}function updateTocCurrentMark() {const rows = [...document.querySelectorAll("#toc-list .toc-item")].map(row => /** @type {HTMLElement} */ (row));if (readerContext.documentState.pageCount > 1 && readerContext.documentState.page > 0) {const entries = readerContext.navigationState.tocEntries;let pageIndex = -1;15 unmodified lines}if (pageIndex >= 0) readerContext.updateNavigationState({ currentChapterIndex: pageIndex });}for (const row of rows) {const index = Number(row.dataset.tocIndex);let mark = /** @type {HTMLElement | null} */ (row.querySelector(".toc-current-mark"));if (!mark) {mark = document.createElement("span");mark.className = "toc-current-mark";mark.setAttribute("aria-hidden", "true");mark.textContent = "✓";row.appendChild(mark);}mark.hidden = index !== readerContext.navigationState.currentChapterIndex;row.classList.toggle("is-current", index === readerContext.navigationState.currentChapterIndex);const link = row.querySelector('[role="link"]');if (index === readerContext.navigationState.currentChapterIndex) link?.setAttribute("aria-current", "location");else link?.removeAttribute("aria-current");}}function syncTocTab() {160 unmodified lines16116216316416516616716816917017117217317417517611 unmodified lines18818919019119219331 unmodified lines225226227228229230231147 unmodified lines37938038138238338438538638738838939039139239339439539639739839940040140240340440540640715 unmodified lines423424425426427428429160 unmodified lineslink.className = "panel-item-main";link.textContent = entry.label;link.title = entry.label;const mark = document.createElement("span");mark.className = "toc-current-mark";mark.setAttribute("aria-hidden", "true");mark.textContent = "✓";mark.hidden = true;row.append(link, mark);if (entry.group) {row.classList.add("toc-group");link.setAttribute("role", "heading");link.setAttribute("aria-level", String(Math.min(6, (entry.depth || 0) + 1)));return row;}link.tabIndex = 0;11 unmodified linesactivate();}});return row;}31 unmodified linesif (!row) {row = readerContext.createTocRow(state.entries[index], index);row.classList.add("toc-virtual-row");if (state.query) readerContext.highlightPanelItem(/** @type {HTMLElement} */ (row.firstElementChild), state.query);cache.rows.set(index, row);}const top = `${position * readerContext.TOC_VIRTUAL_ROW_HEIGHT}px`;147 unmodified linespageLookupEntries = entries;}/** @param {Element} row @param {boolean} current */function markTocRow(row, current) {const mark = /** @type {HTMLElement} */ (row.querySelector(".toc-current-mark"));mark.hidden = !current;row.classList.toggle("is-current", current);const link = row.querySelector('[role="link"]');if (current) link?.setAttribute("aria-current", "location");else link?.removeAttribute("aria-current");}// Track the node, not just the index: filtering can replace it at the same index./** @type {Element | null | undefined} */let markedRow;function syncMarkedTocRow() {const index = readerContext.navigationState.currentChapterIndex, state = readerContext.tocVirtualState;const row = state ? virtualTocRows.get(state)?.rows.get(index) : document.getElementById("toc-list")?.children.item(index);if (markedRow === row) return;if (markedRow?.isConnected) markTocRow(markedRow, false);markedRow = row;if (row) markTocRow(row, true);}function updateTocCurrentMark() {if (readerContext.documentState.pageCount > 1 && readerContext.documentState.page > 0) {const entries = readerContext.navigationState.tocEntries;let pageIndex = -1;15 unmodified lines}if (pageIndex >= 0) readerContext.updateNavigationState({ currentChapterIndex: pageIndex });}syncMarkedTocRow();}function syncTocTab() {
74 unmodified lines757677787980300 unmodified lines381382383384385386387388129 unmodified lines51851952052152252315 unmodified lines5395405415425435445456 unmodified lines5525535545555565575585596 unmodified lines56656756856957057174 unmodified lineswindow.__toc={nav:()=>navigationState, jump:i=>navigateTocEntry(i),set:setToc, setPageCount:count=>updateDocumentState({pageCount:count}),setPage:page=>{updateDocumentState({page});updateTocCurrentMark()},state:()=>tocVirtualState,align:(selector, offset)=>alignReaderDestination(document.querySelector(selector), offset || 0),hold:(target, offset)=>holdReaderDestination(target, offset),300 unmodified lines# Index 60..119 are the "第N章 第二节" sub-entries.for chapter in (2, 30, 58):self.click_entry(60 + chapter - 1)self.assertLess(abs(self.offset_of(f'#sec-{chapter}-b') or 99), 2,f"第{chapter}章 第二节 fragment did not land")self.assertEqual(self.landed_chapter(), chapter)def test_large_chapter_yields_and_aborted_reader_never_mounts_partial_article(self):129 unmodified linesself.assertEqual(self.landed_chapter(), index+1)if not self.panel_open(): self.page.locator('#history').click()def test_virtualized_directory_reuses_rows_and_keeps_keyboard_focus(self):self.page.emulate_media(reduced_motion='reduce')self.page.set_viewport_size({'width':1200,'height':800})15 unmodified linesconst focused=document.activeElement, original=[...list.children];const observer=new MutationObserver(records=>mutations.push(...records));let mutations=[];observer.observe(list,{childList:true});const frame=()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));const results=[];try {6 unmodified linesmutations.push(...observer.takeRecords());const after=[...list.children], indices=after.map(row=>Number(row.dataset.tocIndex));results.push({added:mutations.reduce((n,r)=>n+r.addedNodes.length,0),removed:mutations.reduce((n,r)=>n+r.removedNodes.length,0),fresh:after.filter(row=>!before.includes(row)).length,retained:before.filter(row=>indices.includes(Number(row.dataset.tocIndex))).every(row=>after.includes(row)),6 unmodified linesreturn results;}''')for result, shift, changed in zip(results,(0,1,0),(0,1,1)):self.assertEqual(result['added'],changed)self.assertEqual(result['removed'],changed)self.assertEqual(result['fresh'],changed)74 unmodified lines75767778798081300 unmodified lines382383384385386387388389390129 unmodified lines52052152252352452552652752852953053153253353453553653753853954054154215 unmodified lines5585595605615625635646 unmodified lines5715725735745755765775785796 unmodified lines58658758858959059159274 unmodified lineswindow.__toc={nav:()=>navigationState, jump:i=>navigateTocEntry(i),set:setToc, setPageCount:count=>updateDocumentState({pageCount:count}),setPage:page=>{updateDocumentState({page});updateTocCurrentMark()},setCurrent:index=>{updateNavigationState({currentChapterIndex:index});updateTocCurrentMark()},state:()=>tocVirtualState,align:(selector, offset)=>alignReaderDestination(document.querySelector(selector), offset || 0),hold:(target, offset)=>holdReaderDestination(target, offset),300 unmodified lines# Index 60..119 are the "第N章 第二节" sub-entries.for chapter in (2, 30, 58):self.click_entry(60 + chapter - 1)offset = self.offset_of(f'#sec-{chapter}-b')self.assertIsNotNone(offset, f"第{chapter}章 第二节 fragment is missing")self.assertLess(abs(offset), 2, f"第{chapter}章 第二节 fragment did not land")self.assertEqual(self.landed_chapter(), chapter)def test_large_chapter_yields_and_aborted_reader_never_mounts_partial_article(self):129 unmodified linesself.assertEqual(self.landed_chapter(), index+1)if not self.panel_open(): self.page.locator('#history').click()def test_current_mark_only_changes_rows_that_enter_or_leave_current(self):self.open_chapters(12)metrics=self.page.evaluate('''()=>{const list=document.querySelector('#toc-list'), rows=[...list.children];__toc.setCurrent(1);const observer=new MutationObserver(()=>{});observer.observe(list,{subtree:true,attributes:true,attributeFilter:['hidden','class','aria-current']});__toc.setCurrent(1);const repeated=observer.takeRecords().length;__toc.setCurrent(3);const touched=[...new Set(observer.takeRecords().map(r=>Number(r.target.closest('.toc-item').dataset.tocIndex)))].sort();observer.disconnect();const current=[...list.querySelectorAll('[aria-current="location"]')].map(link=>Number(link.parentElement.dataset.tocIndex));return {repeated,touched,current,sameRows:rows.every((row,i)=>row===list.children[i])};}''')self.assertEqual(metrics,dict(repeated=0,touched=[1,3],current=[3],sameRows=True))def test_virtualized_directory_reuses_rows_and_keeps_keyboard_focus(self):self.page.emulate_media(reduced_motion='reduce')self.page.set_viewport_size({'width':1200,'height':800})15 unmodified linesconst focused=document.activeElement, original=[...list.children];const observer=new MutationObserver(records=>mutations.push(...records));let mutations=[];observer.observe(list,{childList:true,subtree:true,attributes:true,attributeFilter:['hidden','class','aria-current']});const frame=()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));const results=[];try {6 unmodified linesmutations.push(...observer.takeRecords());const after=[...list.children], indices=after.map(row=>Number(row.dataset.tocIndex));results.push({markerWrites:mutations.filter(r=>r.type==='attributes').length,added:mutations.filter(r=>r.target===list).reduce((n,r)=>n+r.addedNodes.length,0),removed:mutations.filter(r=>r.target===list).reduce((n,r)=>n+r.removedNodes.length,0),fresh:after.filter(row=>!before.includes(row)).length,retained:before.filter(row=>indices.includes(Number(row.dataset.tocIndex))).every(row=>after.includes(row)),6 unmodified linesreturn results;}''')for result, shift, changed in zip(results,(0,1,0),(0,1,1)):self.assertEqual(result['markerWrites'],0,result)self.assertEqual(result['added'],changed)self.assertEqual(result['removed'],changed)self.assertEqual(result['fresh'],changed)
static/reader/ui/reader-toc.mjs+30-20
tests/reader/browser/test_reader_toc_navigation.py+26-5