vomebook commited on
Commit
c0f9fe7
·
1 Parent(s): cf9e90b

Update only the rows affected by Reader TOC current marking

Browse files
static/reader/ui/reader-toc.mjs CHANGED
@@ -161,11 +161,16 @@ export function createReaderToc(readerContext) {
161
  link.className = "panel-item-main";
162
  link.textContent = entry.label;
163
  link.title = entry.label;
 
 
 
 
 
 
164
  if (entry.group) {
165
  row.classList.add("toc-group");
166
  link.setAttribute("role", "heading");
167
  link.setAttribute("aria-level", String(Math.min(6, (entry.depth || 0) + 1)));
168
- row.appendChild(link);
169
  return row;
170
  }
171
  link.tabIndex = 0;
@@ -183,7 +188,6 @@ export function createReaderToc(readerContext) {
183
  activate();
184
  }
185
  });
186
- row.appendChild(link);
187
  return row;
188
  }
189
 
@@ -221,7 +225,7 @@ export function createReaderToc(readerContext) {
221
  if (!row) {
222
  row = readerContext.createTocRow(state.entries[index], index);
223
  row.classList.add("toc-virtual-row");
224
- if (state.query) readerContext.highlightPanelItem(row, state.query);
225
  cache.rows.set(index, row);
226
  }
227
  const top = `${position * readerContext.TOC_VIRTUAL_ROW_HEIGHT}px`;
@@ -375,8 +379,29 @@ export function createReaderToc(readerContext) {
375
  pageLookupEntries = entries;
376
  }
377
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
378
  function updateTocCurrentMark() {
379
- const rows = [...document.querySelectorAll("#toc-list .toc-item")].map(row => /** @type {HTMLElement} */ (row));
380
  if (readerContext.documentState.pageCount > 1 && readerContext.documentState.page > 0) {
381
  const entries = readerContext.navigationState.tocEntries;
382
  let pageIndex = -1;
@@ -398,22 +423,7 @@ export function createReaderToc(readerContext) {
398
  }
399
  if (pageIndex >= 0) readerContext.updateNavigationState({ currentChapterIndex: pageIndex });
400
  }
401
- for (const row of rows) {
402
- const index = Number(row.dataset.tocIndex);
403
- let mark = /** @type {HTMLElement | null} */ (row.querySelector(".toc-current-mark"));
404
- if (!mark) {
405
- mark = document.createElement("span");
406
- mark.className = "toc-current-mark";
407
- mark.setAttribute("aria-hidden", "true");
408
- mark.textContent = "✓";
409
- row.appendChild(mark);
410
- }
411
- mark.hidden = index !== readerContext.navigationState.currentChapterIndex;
412
- row.classList.toggle("is-current", index === readerContext.navigationState.currentChapterIndex);
413
- const link = row.querySelector('[role="link"]');
414
- if (index === readerContext.navigationState.currentChapterIndex) link?.setAttribute("aria-current", "location");
415
- else link?.removeAttribute("aria-current");
416
- }
417
  }
418
 
419
  function syncTocTab() {
 
161
  link.className = "panel-item-main";
162
  link.textContent = entry.label;
163
  link.title = entry.label;
164
+ const mark = document.createElement("span");
165
+ mark.className = "toc-current-mark";
166
+ mark.setAttribute("aria-hidden", "true");
167
+ mark.textContent = "✓";
168
+ mark.hidden = true;
169
+ row.append(link, mark);
170
  if (entry.group) {
171
  row.classList.add("toc-group");
172
  link.setAttribute("role", "heading");
173
  link.setAttribute("aria-level", String(Math.min(6, (entry.depth || 0) + 1)));
 
174
  return row;
175
  }
176
  link.tabIndex = 0;
 
188
  activate();
189
  }
190
  });
 
191
  return row;
192
  }
193
 
 
225
  if (!row) {
226
  row = readerContext.createTocRow(state.entries[index], index);
227
  row.classList.add("toc-virtual-row");
228
+ if (state.query) readerContext.highlightPanelItem(/** @type {HTMLElement} */ (row.firstElementChild), state.query);
229
  cache.rows.set(index, row);
230
  }
231
  const top = `${position * readerContext.TOC_VIRTUAL_ROW_HEIGHT}px`;
 
379
  pageLookupEntries = entries;
380
  }
381
 
382
+ /** @param {Element} row @param {boolean} current */
383
+ function markTocRow(row, current) {
384
+ const mark = /** @type {HTMLElement} */ (row.querySelector(".toc-current-mark"));
385
+ mark.hidden = !current;
386
+ row.classList.toggle("is-current", current);
387
+ const link = row.querySelector('[role="link"]');
388
+ if (current) link?.setAttribute("aria-current", "location");
389
+ else link?.removeAttribute("aria-current");
390
+ }
391
+
392
+ // Track the node, not just the index: filtering can replace it at the same index.
393
+ /** @type {Element | null | undefined} */
394
+ let markedRow;
395
+ function syncMarkedTocRow() {
396
+ const index = readerContext.navigationState.currentChapterIndex, state = readerContext.tocVirtualState;
397
+ const row = state ? virtualTocRows.get(state)?.rows.get(index) : document.getElementById("toc-list")?.children.item(index);
398
+ if (markedRow === row) return;
399
+ if (markedRow?.isConnected) markTocRow(markedRow, false);
400
+ markedRow = row;
401
+ if (row) markTocRow(row, true);
402
+ }
403
+
404
  function updateTocCurrentMark() {
 
405
  if (readerContext.documentState.pageCount > 1 && readerContext.documentState.page > 0) {
406
  const entries = readerContext.navigationState.tocEntries;
407
  let pageIndex = -1;
 
423
  }
424
  if (pageIndex >= 0) readerContext.updateNavigationState({ currentChapterIndex: pageIndex });
425
  }
426
+ syncMarkedTocRow();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
427
  }
428
 
429
  function syncTocTab() {
tests/reader/browser/test_reader_toc_navigation.py CHANGED
@@ -75,6 +75,7 @@ class TocNavigationTests(unittest.TestCase):
75
  window.__toc={nav:()=>navigationState, jump:i=>navigateTocEntry(i),
76
  set:setToc, setPageCount:count=>updateDocumentState({pageCount:count}),
77
  setPage:page=>{updateDocumentState({page});updateTocCurrentMark()},
 
78
  state:()=>tocVirtualState,
79
  align:(selector, offset)=>alignReaderDestination(document.querySelector(selector), offset || 0),
80
  hold:(target, offset)=>holdReaderDestination(target, offset),
@@ -381,8 +382,9 @@ class TocNavigationTests(unittest.TestCase):
381
  # Index 60..119 are the "第N章 第二节" sub-entries.
382
  for chapter in (2, 30, 58):
383
  self.click_entry(60 + chapter - 1)
384
- self.assertLess(abs(self.offset_of(f'#sec-{chapter}-b') or 99), 2,
385
- f"第{chapter}章 第二节 fragment did not land")
 
386
  self.assertEqual(self.landed_chapter(), chapter)
387
 
388
  def test_large_chapter_yields_and_aborted_reader_never_mounts_partial_article(self):
@@ -518,6 +520,23 @@ class TocNavigationTests(unittest.TestCase):
518
  self.assertEqual(self.landed_chapter(), index+1)
519
  if not self.panel_open(): self.page.locator('#history').click()
520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521
  def test_virtualized_directory_reuses_rows_and_keeps_keyboard_focus(self):
522
  self.page.emulate_media(reduced_motion='reduce')
523
  self.page.set_viewport_size({'width':1200,'height':800})
@@ -539,7 +558,7 @@ class TocNavigationTests(unittest.TestCase):
539
  const focused=document.activeElement, original=[...list.children];
540
  const observer=new MutationObserver(records=>mutations.push(...records));
541
  let mutations=[];
542
- observer.observe(list,{childList:true});
543
  const frame=()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
544
  const results=[];
545
  try {
@@ -552,8 +571,9 @@ class TocNavigationTests(unittest.TestCase):
552
  mutations.push(...observer.takeRecords());
553
  const after=[...list.children], indices=after.map(row=>Number(row.dataset.tocIndex));
554
  results.push({
555
- added:mutations.reduce((n,r)=>n+r.addedNodes.length,0),
556
- removed:mutations.reduce((n,r)=>n+r.removedNodes.length,0),
 
557
  fresh:after.filter(row=>!before.includes(row)).length,
558
  retained:before.filter(row=>indices.includes(Number(row.dataset.tocIndex)))
559
  .every(row=>after.includes(row)),
@@ -566,6 +586,7 @@ class TocNavigationTests(unittest.TestCase):
566
  return results;
567
  }''')
568
  for result, shift, changed in zip(results,(0,1,0),(0,1,1)):
 
569
  self.assertEqual(result['added'],changed)
570
  self.assertEqual(result['removed'],changed)
571
  self.assertEqual(result['fresh'],changed)
 
75
  window.__toc={nav:()=>navigationState, jump:i=>navigateTocEntry(i),
76
  set:setToc, setPageCount:count=>updateDocumentState({pageCount:count}),
77
  setPage:page=>{updateDocumentState({page});updateTocCurrentMark()},
78
+ setCurrent:index=>{updateNavigationState({currentChapterIndex:index});updateTocCurrentMark()},
79
  state:()=>tocVirtualState,
80
  align:(selector, offset)=>alignReaderDestination(document.querySelector(selector), offset || 0),
81
  hold:(target, offset)=>holdReaderDestination(target, offset),
 
382
  # Index 60..119 are the "第N章 第二节" sub-entries.
383
  for chapter in (2, 30, 58):
384
  self.click_entry(60 + chapter - 1)
385
+ offset = self.offset_of(f'#sec-{chapter}-b')
386
+ self.assertIsNotNone(offset, f"第{chapter}章 第二节 fragment is missing")
387
+ self.assertLess(abs(offset), 2, f"第{chapter}章 第二节 fragment did not land")
388
  self.assertEqual(self.landed_chapter(), chapter)
389
 
390
  def test_large_chapter_yields_and_aborted_reader_never_mounts_partial_article(self):
 
520
  self.assertEqual(self.landed_chapter(), index+1)
521
  if not self.panel_open(): self.page.locator('#history').click()
522
 
523
+ def test_current_mark_only_changes_rows_that_enter_or_leave_current(self):
524
+ self.open_chapters(12)
525
+ metrics=self.page.evaluate('''()=>{
526
+ const list=document.querySelector('#toc-list'), rows=[...list.children];
527
+ __toc.setCurrent(1);
528
+ const observer=new MutationObserver(()=>{});
529
+ observer.observe(list,{subtree:true,attributes:true,attributeFilter:['hidden','class','aria-current']});
530
+ __toc.setCurrent(1);
531
+ const repeated=observer.takeRecords().length;
532
+ __toc.setCurrent(3);
533
+ const touched=[...new Set(observer.takeRecords().map(r=>Number(r.target.closest('.toc-item').dataset.tocIndex)))].sort();
534
+ observer.disconnect();
535
+ const current=[...list.querySelectorAll('[aria-current="location"]')].map(link=>Number(link.parentElement.dataset.tocIndex));
536
+ return {repeated,touched,current,sameRows:rows.every((row,i)=>row===list.children[i])};
537
+ }''')
538
+ self.assertEqual(metrics,dict(repeated=0,touched=[1,3],current=[3],sameRows=True))
539
+
540
  def test_virtualized_directory_reuses_rows_and_keeps_keyboard_focus(self):
541
  self.page.emulate_media(reduced_motion='reduce')
542
  self.page.set_viewport_size({'width':1200,'height':800})
 
558
  const focused=document.activeElement, original=[...list.children];
559
  const observer=new MutationObserver(records=>mutations.push(...records));
560
  let mutations=[];
561
+ observer.observe(list,{childList:true,subtree:true,attributes:true,attributeFilter:['hidden','class','aria-current']});
562
  const frame=()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
563
  const results=[];
564
  try {
 
571
  mutations.push(...observer.takeRecords());
572
  const after=[...list.children], indices=after.map(row=>Number(row.dataset.tocIndex));
573
  results.push({
574
+ markerWrites:mutations.filter(r=>r.type==='attributes').length,
575
+ added:mutations.filter(r=>r.target===list).reduce((n,r)=>n+r.addedNodes.length,0),
576
+ removed:mutations.filter(r=>r.target===list).reduce((n,r)=>n+r.removedNodes.length,0),
577
  fresh:after.filter(row=>!before.includes(row)).length,
578
  retained:before.filter(row=>indices.includes(Number(row.dataset.tocIndex)))
579
  .every(row=>after.includes(row)),
 
586
  return results;
587
  }''')
588
  for result, shift, changed in zip(results,(0,1,0),(0,1,1)):
589
+ self.assertEqual(result['markerWrites'],0,result)
590
  self.assertEqual(result['added'],changed)
591
  self.assertEqual(result['removed'],changed)
592
  self.assertEqual(result['fresh'],changed)