vomebook commited on
Commit
3fed1fd
·
1 Parent(s): 81c84ae

Measure shared chapter TOC targets once per marker pass

Browse files
static/reader/ui/reader-toc.mjs CHANGED
@@ -121,9 +121,18 @@ export function createReaderToc(readerContext) {
121
  currentPosition = -Infinity,
122
  first = -1,
123
  firstPosition = Infinity;
 
 
 
 
124
  for (const [index, entry] of readerContext.navigationState.tocEntries.entries()) {
125
- if (!entry.target?.isConnected) continue;
126
- const position = entry.target.getBoundingClientRect().top;
 
 
 
 
 
127
  if (position <= marker && (position > currentPosition || (position === currentPosition && index > current))) {
128
  current = index;
129
  currentPosition = position;
 
121
  currentPosition = -Infinity,
122
  first = -1,
123
  firstPosition = Infinity;
124
+ // CHM fallbacks and fragment aliases can share a target. Reuse its top
125
+ // only in this read pass: layout and scroll can move it before the next.
126
+ /** @type {Map<Element, number>} */
127
+ const targetTops = new Map();
128
  for (const [index, entry] of readerContext.navigationState.tocEntries.entries()) {
129
+ const target = entry.target;
130
+ if (!target?.isConnected) continue;
131
+ let position = targetTops.get(target);
132
+ if (position === undefined) {
133
+ position = target.getBoundingClientRect().top;
134
+ targetTops.set(target, position);
135
+ }
136
  if (position <= marker && (position > currentPosition || (position === currentPosition && index > current))) {
137
  current = index;
138
  currentPosition = position;
tests/reader/browser/test_reader_toc_navigation.py CHANGED
@@ -43,7 +43,7 @@ class TocNavigationTests(unittest.TestCase):
43
  route.fulfill(response=response, body=response.text() + '''
44
  window.__replaceTocForSearch=setToc;
45
  window.__toc={nav:()=>navigationState, jump:i=>navigateTocEntry(i),
46
- set:setToc, filter:()=>filterPanel(document.querySelector('#toc-panel')),
47
  setPageCount:count=>updateDocumentState({pageCount:count}),
48
  setPage:page=>{updateDocumentState({page});updateTocCurrentMark()},
49
  setCurrent:index=>{updateNavigationState({currentChapterIndex:index});updateTocCurrentMark()},
@@ -490,6 +490,82 @@ class TocNavigationTests(unittest.TestCase):
490
  self.assertEqual(result['unsafe'],0)
491
  self.assertIn('chapter head',result['head'])
492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
493
  def test_chapter_target_updates_only_visit_the_owned_toc_once(self):
494
  self.expose()
495
  # Drive demand loads and the real virtualizer explicitly, without ambient prefetch.
 
43
  route.fulfill(response=response, body=response.text() + '''
44
  window.__replaceTocForSearch=setToc;
45
  window.__toc={nav:()=>navigationState, jump:i=>navigateTocEntry(i),
46
+ set:setToc, sync:()=>syncHeadingLocation(), filter:()=>filterPanel(document.querySelector('#toc-panel')),
47
  setPageCount:count=>updateDocumentState({pageCount:count}),
48
  setPage:page=>{updateDocumentState({page});updateTocCurrentMark()},
49
  setCurrent:index=>{updateNavigationState({currentChapterIndex:index});updateTocCurrentMark()},
 
490
  self.assertEqual(result['unsafe'],0)
491
  self.assertIn('chapter head',result['head'])
492
 
493
+ def test_chapter_scroll_geometry_census_with_shared_toc_targets(self):
494
+ self.expose()
495
+
496
+ def expose_window(route):
497
+ response = route.fetch()
498
+ script = response.text()
499
+ needle = ' function scheduleChapterWindow() {'
500
+ self.assertIn(needle, script)
501
+ route.fulfill(response=response, body=script.replace(needle,
502
+ ' window.__refreshChapterWindow = refreshChapterWindow;\n' + needle, 1))
503
+
504
+ self.page.route('**/static/reader/formats/reader-chapter-format.mjs*', expose_window)
505
+ prose = '<p>A line in the converted chapter.</p>' * 120
506
+ body = ('<p id="lead" style="height:120px"><a href="#chm-page-1">First page</a> '
507
+ '<a href="#chm-page-2">Second page</a></p>'
508
+ f'<section id="chm-page-1"><h1>One</h1>{prose}</section>'
509
+ f'<section id="chm-page-2"><h1>Two</h1>{prose}</section>')
510
+ # A merged CHM can have many entries with no recoverable fragment. Each
511
+ # still participates in tie-breaking even though they share the article.
512
+ entries = [(f'Unresolved entry {i}', '') for i in range(120)] + [
513
+ ('First page', ''), ('Second page', ''), ('Second page alias', 'chm-page-2'), ('Missing', 'missing')]
514
+ manifest = {'version': 1, 'kind': 'epub-chapters', 'chapters': [
515
+ {'index': 1, 'path': 'chapters/chapter-0001.xhtml', 'source_path': 'chm-fallback.html', 'bytes': len(body)}
516
+ ], 'toc': [{'title': label, 'chapter': 1, 'fragment': fragment, 'depth': 0} for label, fragment in entries]}
517
+ self.page.route('**/api/reader-bucket-resource**', lambda route: route.fulfill(json=manifest)
518
+ if 'chapter-manifest' in route.request.url else route.fulfill(content_type='text/html', body=body))
519
+ source = ('https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/chm/'
520
+ + 'a' * 64 + '/1234567890abcdef/chapter-manifest.json')
521
+ self.page.goto(self.origin + support.PREFIX + '/static/reader.html?' +
522
+ urlencode(dict(url=source, ext='epub-chapters')), wait_until='domcontentloaded')
523
+ self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready'")
524
+ result = self.page.evaluate('''() => {
525
+ const viewport = document.querySelector('#viewport');
526
+ const article = viewport.querySelector('.reader-epub-chapter');
527
+ const second = article.querySelector('#chm-page-2');
528
+ const placeholder = document.createElement('button');
529
+ placeholder.className = 'reader-chapter-sentinel reader-chapter-placeholder';
530
+ placeholder.dataset.chapter = '0';
531
+ placeholder.style.height = '120px';
532
+ article.before(placeholder);
533
+ viewport.scrollTop += second.getBoundingClientRect().top - viewport.getBoundingClientRect().top - 4;
534
+ const entries = __toc.nav().tocEntries;
535
+ const connected = entries.map(entry => entry.target).filter(target => target?.isConnected);
536
+ const rect = Element.prototype.getBoundingClientRect;
537
+ const census = run => {
538
+ const nodes = new Set();
539
+ let calls = 0;
540
+ Element.prototype.getBoundingClientRect = function () {
541
+ nodes.add(this);
542
+ calls++;
543
+ return rect.call(this);
544
+ };
545
+ try { run(); } finally { Element.prototype.getBoundingClientRect = rect; }
546
+ return [nodes.size, calls];
547
+ };
548
+ const current = () => [__toc.nav().currentChapterIndex,
549
+ Number(document.querySelector('#toc-list .is-current')?.dataset.tocIndex)];
550
+ // Sample the real synchronous scroll listener and the two independently
551
+ // scheduled passes in isolation, before any queued frame can run.
552
+ const remember = census(() => viewport.dispatchEvent(new Event('scroll')));
553
+ const windowRows = census(__refreshChapterWindow);
554
+ const toc = census(__toc.sync);
555
+ const before = current();
556
+ const scroll = viewport.scrollTop;
557
+ article.querySelector('#lead').style.height = '240px';
558
+ viewport.scrollTop = scroll;
559
+ const lateToc = census(__toc.sync);
560
+ return {entries: [entries.length, connected.length, new Set(connected).size],
561
+ remember, windowRows, toc, lateToc, before, after: current()};
562
+ }''')
563
+ # Counts are [unique measured nodes, rectangle reads]. The unmodified
564
+ # reader reported [4, 124] for each TOC pass in both builds. Remember
565
+ # (244 candidates + viewport) and window rows are unchanged.
566
+ self.assertEqual(result, dict(entries=[124, 123, 3], remember=[245, 245], windowRows=[3, 3],
567
+ toc=[4, 4], lateToc=[4, 4], before=[122, 122], after=[120, 120]))
568
+
569
  def test_chapter_target_updates_only_visit_the_owned_toc_once(self):
570
  self.expose()
571
  # Drive demand loads and the real virtualizer explicitly, without ambient prefetch.