Debian Codegraph @

src/pyj/range_utils.pyj

raw
1 # vim:fileencoding=utf-8
2 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
3 # globals: NodeFilter, Range
4 from __python__ import bound_methods, hash_literals
5
6
7 def is_non_empty_text_node(node):
8 return (node.nodeType is Node.TEXT_NODE or node.nodeType is Node.CDATA_SECTION_NODE) and node.nodeValue.length > 0
9
10
11 def is_element_visible(elem):
12 s = window.getComputedStyle(elem)
13 return s.display is not 'none' and s.visibility is not 'hidden'
14
15
16 def is_node_visible(node):
17 if node.nodeType is not Node.ELEMENT_NODE:
18 node = node.parentElement
19 if not node:
20 return False
21 current = node
22 while current:
23 if not is_element_visible(current):
24 return False
25 current = current.parentElement
26 return True
27
28
29 def select_nodes_from_range(r, predicate):
30 parent = r.commonAncestorContainer
31 doc = parent.ownerDocument or document
32 iterator = doc.createNodeIterator(parent)
33 in_range = False
34 ans = []
35 check_for_end = not (r.startContainer.isSameNode(r.endContainer) and r.startContainer.isSameNode(parent))
36 while True:
37 node = iterator.nextNode()
38 if not node:
39 break
40 if not in_range and node.isSameNode(r.startContainer):
41 in_range = True
42 if in_range:
43 if predicate(node):
44 ans.push(node)
45 if check_for_end and node.isSameNode(r.endContainer):
46 break
47 return ans
48
49
50 def select_first_node_from_range(r, predicate):
51 parent = r.commonAncestorContainer
52 doc = parent.ownerDocument or document
53 iterator = doc.createNodeIterator(parent)
54 in_range = False
55 check_for_end = not (r.startContainer.isSameNode(r.endContainer) and r.startContainer.isSameNode(parent))
56 while True:
57 node = iterator.nextNode()
58 if not node:
59 break
60 if not in_range and node.isSameNode(r.startContainer):
61 in_range = True
62 if in_range:
63 if predicate(node):
64 return node
65 if check_for_end and node.isSameNode(r.endContainer):
66 break
67
68
69 def text_nodes_in_range(r):
70 return select_nodes_from_range(r, is_non_empty_text_node)
71
72
73 def all_annots_in_range(r, annot_id_uuid_map, ans):
74 parent = r.commonAncestorContainer
75 doc = parent.ownerDocument or document
76 iterator = doc.createNodeIterator(parent)
77 is_full_tree = parent is doc.documentElement
78 in_range = is_full_tree
79 check_for_end = not is_full_tree and not (r.startContainer.isSameNode(r.endContainer) and r.startContainer.isSameNode(parent))
80 while True:
81 node = iterator.nextNode()
82 if not node:
83 break
84 if not in_range and node.isSameNode(r.startContainer):
85 in_range = True
86 if in_range:
87 if node.dataset and node.dataset.calibreRangeWrapper:
88 annot_id = annot_id_uuid_map[node.dataset.calibreRangeWrapper]
89 if annot_id:
90 if not ans:
91 return annot_id
92 ans[annot_id] = True
93 if check_for_end and node.isSameNode(r.endContainer):
94 break
95 return ans
96
97
98 def first_annot_in_range(r, annot_id_uuid_map):
99 return all_annots_in_range(r, annot_id_uuid_map)
100
101
102 def all_annots_in_selection(sel, annot_id_uuid_map):
103 ans = v'{}'
104 for i in range(sel.rangeCount):
105 all_annots_in_range(sel.getRangeAt(i), annot_id_uuid_map, ans)
106 return Object.keys(ans)
107
108
109 def remove(node):
110 if node.parentNode:
111 node.parentNode.removeChild(node)
112
113
114 def replace_node(replacement, node):
115 p = node.parentNode
116 p.insertBefore(replacement, node)
117 remove(node)
118 return p
119
120
121 def unwrap(node):
122 r = (node.ownerDocument or document).createRange()
123 r.selectNodeContents(node)
124 p = replace_node(r.extractContents(), node)
125 if p:
126 p.normalize()
127
128
129 def unwrap_crw(crw):
130 for node in document.querySelectorAll(f'span[data-calibre-range-wrapper="{crw}"]'):
131 unwrap(node)
132
133
134 def unwrap_all_crw():
135 for node in document.querySelectorAll('span[data-calibre-range-wrapper]'):
136 unwrap(node)
137
138
139 def select_crw(crw):
140 nodes = document.querySelectorAll(f'span[data-calibre-range-wrapper="{crw}"]')
141 if nodes and nodes.length:
142 r = document.createRange()
143 r.setStart(nodes[0].firstChild, 0)
144 r.setEnd(nodes[-1].lastChild, nodes[-1].lastChild.nodeValue.length)
145 sel = window.getSelection()
146 sel.removeAllRanges()
147 sel.addRange(r)
148 return True
149 print(f'range-wrapper: {crw} does not exist')
150 return False
151
152
153 def wrap_range(r, wrapper):
154 try:
155 r.surroundContents(wrapper)
156 except:
157 wrapper.appendChild(r.extractContents())
158 r.insertNode(wrapper)
159
160
161 def create_wrapper_function(wrapper_elem, r, intersecting_wrappers, process_wrapper, all_wrappers):
162 start_node = r.startContainer
163 end_node = r.endContainer
164 start_offset = r.startOffset
165 end_offset = r.endOffset
166
167 def wrap_node(node):
168 nonlocal start_node, end_node, start_offset, end_offset
169 current_range = (node.ownerDocument or document).createRange()
170 current_wrapper = wrapper_elem.cloneNode()
171 current_range.selectNodeContents(node)
172 # adjust start and end in case the current node is one of the
173 # boundaries of the original range
174 if node.isSameNode(start_node):
175 current_range.setStart(node, start_offset)
176 start_node = current_wrapper
177 start_offset = 0
178 if node.isSameNode(end_node):
179 current_range.setEnd(node, end_offset)
180 end_node = current_wrapper
181 end_offset = 1
182 if current_range.collapsed:
183 # Don't wrap empty ranges. This is needed otherwise two adjacent
184 # selections of text will incorrectly be detected as overlapping.
185 # For example: highlight abc then def in the word abcdef here the
186 # second highlight's first range is the collapsed range at the end
187 # of <span wrapper-for-first-highlight>abc<span wrapper-for-2nd></span></span>
188 return
189 crw = node.parentNode?.dataset?.calibreRangeWrapper
190 if crw:
191 intersecting_wrappers[crw] = True
192 wrap_range(current_range, current_wrapper)
193 if process_wrapper:
194 process_wrapper(current_wrapper)
195 all_wrappers.push(current_wrapper)
196
197 return wrap_node
198
199
200 wrapper_counter = 0
201
202
203 def wrap_text_in_range(styler, r, class_to_add_to_last, process_wrapper):
204 if not r:
205 sel = window.getSelection()
206 if not sel or not sel.rangeCount:
207 return None, []
208 r = sel.getRangeAt(0)
209 if r.isCollapsed:
210 return None, []
211
212 wrapper_elem = document.createElement('span')
213 wrapper_elem.dataset.calibreRangeWrapper = v'++wrapper_counter' + ''
214 if styler:
215 styler(wrapper_elem)
216
217 intersecting_wrappers = {}
218 all_wrappers = []
219 wrap_node = create_wrapper_function(wrapper_elem, r, intersecting_wrappers, process_wrapper, all_wrappers)
220 text_nodes_in_range(r).map(wrap_node)
221 ancestor = r.commonAncestorContainer
222 if ancestor.nodeType is Node.TEXT_NODE:
223 ancestor = ancestor.parentNode
224 # remove any empty text nodes created by surroundContents() on either
225 # side of the wrapper. This happens for instance on Chrome when
226 # wrapping all text inside <i>some text</i>
227 ancestor.normalize()
228 crw = wrapper_elem.dataset.calibreRangeWrapper
229 v'delete intersecting_wrappers[crw]'
230 if class_to_add_to_last and all_wrappers.length:
231 all_wrappers[-1].classList.add(class_to_add_to_last)
232 return crw, Object.keys(intersecting_wrappers)
233
234
235 def last_span_for_crw(crw):
236 nodes = document.querySelectorAll(f'span[data-calibre-range-wrapper="{crw}"]')
237 if nodes and nodes.length:
238 return nodes[-1]
239
240
241 def reset_highlight_counter():
242 nonlocal wrapper_counter
243 wrapper_counter = 0
244
245
246 def get_annot_id_for(node, offset, annot_id_uuid_map):
247 if not node:
248 return
249 if node.nodeType is Node.ELEMENT_NODE:
250 if node.dataset?.calibreRangeWrapper:
251 return annot_id_uuid_map[node.dataset.calibreRangeWrapper]
252 if offset is 0:
253 if node.firstChild?.nodeType is Node.ELEMENT_NODE and node.firstChild.dataset?.calibreRangeWrapper:
254 return annot_id_uuid_map[node.firstChild.dataset.calibreRangeWrapper]
255 elif offset < node.childNodes.length:
256 node = node.childNodes[offset]
257 return get_annot_id_for(node, 0, annot_id_uuid_map)
258 elif node.nodeType is Node.TEXT_NODE:
259 if node.parentNode?.nodeType is Node.ELEMENT_NODE and node.parentNode.dataset?.calibreRangeWrapper:
260 return annot_id_uuid_map[node.parentNode.dataset.calibreRangeWrapper]
261
262
263 def highlight_associated_with_selection(sel, annot_id_uuid_map):
264 # Return the annotation id for a highlight intersecting the selection
265 if sel.rangeCount:
266 annot_id = get_annot_id_for(sel.focusNode, sel.focusOffset, annot_id_uuid_map) or get_annot_id_for(sel.anchorNode, sel.anchorOffset, annot_id_uuid_map)
267 if annot_id:
268 return annot_id
269
270 for v'var i = 0; i < sel.rangeCount; i++':
271 r = sel.getRangeAt(i)
272 annot_id = first_annot_in_range(r, annot_id_uuid_map)
273 if annot_id:
274 return annot_id