| 1 |
# vim:fileencoding=utf-8 |
| 2 |
# License: GPL v3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net> |
| 3 |
from __python__ import bound_methods, hash_literals |
| 4 |
|
| 5 |
from read_book.globals import current_layout_mode, get_boss |
| 6 |
from read_book.viewport import scroll_viewport |
| 7 |
|
| 8 |
anchor_position_cache = {} |
| 9 |
|
| 10 |
|
| 11 |
def invalidate_anchor_position_cache(): |
| 12 |
nonlocal anchor_position_cache |
| 13 |
anchor_position_cache = { |
| 14 |
'layout_mode': current_layout_mode(), 'width': scroll_viewport.width(), 'height': scroll_viewport.height(), |
| 15 |
'positions': v'{}', |
| 16 |
} |
| 17 |
|
| 18 |
|
| 19 |
def ensure_anchor_cache_valid(): |
| 20 |
a = anchor_position_cache |
| 21 |
if a.layout_mode is not current_layout_mode() or a.width is not scroll_viewport.width() or a.height is not scroll_viewport.height(): |
| 22 |
invalidate_anchor_position_cache() |
| 23 |
|
| 24 |
|
| 25 |
def ensure_page_list_target_is_displayed(elem): |
| 26 |
# The stupid EPUB 3 examples have page list links pointing to |
| 27 |
# display:none divs. Sigh. |
| 28 |
if elem and window.getComputedStyle(elem).display is 'none': |
| 29 |
elem.textContent = '' |
| 30 |
elem.setAttribute('style', 'all: revert') |
| 31 |
|
| 32 |
|
| 33 |
def position_for_anchor(anchor, is_page_list_anchor): |
| 34 |
ensure_anchor_cache_valid() |
| 35 |
cache = anchor_position_cache.positions |
| 36 |
val = cache[anchor] |
| 37 |
if val?: |
| 38 |
return val |
| 39 |
anchor_funcs = get_boss().anchor_funcs |
| 40 |
if anchor: |
| 41 |
elem = document.getElementById(anchor) |
| 42 |
if not elem: |
| 43 |
q = document.getElementsByName(anchor) |
| 44 |
if q and q.length: |
| 45 |
elem = q[0] |
| 46 |
else: |
| 47 |
elem = document.body |
| 48 |
if is_page_list_anchor: |
| 49 |
ensure_page_list_target_is_displayed(elem) |
| 50 |
val = anchor_funcs.pos_for_elem(elem) if elem else anchor_funcs.pos_for_elem() |
| 51 |
cache[anchor] = val |
| 52 |
return val |
| 53 |
|
| 54 |
|
| 55 |
def is_anchor_on_screen(anchor): |
| 56 |
pos = position_for_anchor(anchor) |
| 57 |
anchor_funcs = get_boss().anchor_funcs |
| 58 |
return anchor_funcs.visibility(pos) is 0 |