Debian Codegraph @

src/pyj/read_book/highlights.pyj

raw
1 # vim:fileencoding=utf-8
2 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
3 from __python__ import bound_methods, hash_literals
4
5 from elementmaker import E
6 from gettext import gettext as _, ngettext
7
8 from ajax import encode_query
9 from book_list.globals import get_current_query, get_session_data
10 from book_list.theme import get_color
11 from complete import create_search_bar
12 from dom import add_extra_css, build_rule, clear, svgicon, unique_id
13 from modals import (
14 create_custom_dialog, error_dialog, get_text_dialog, question_dialog,
15 warning_dialog
16 )
17 from read_book.globals import current_book, is_dark_theme, runtime, ui_operations
18 from widgets import create_button
19
20 ICON_SIZE_VAL = 3
21 ICON_SIZE_UNIT = 'ex'
22 ICON_SIZE = f'{ICON_SIZE_VAL}{ICON_SIZE_UNIT}'
23 builtin_colors_light = v'''__BUILTIN_COLORS_LIGHT__'''
24 builtin_colors_dark = v'''__BUILTIN_COLORS_DARK__'''
25 builtin_decorations_light = builtin_decorations_dark = v'''__BUILTIN_DECORATIONS__'''
26
27
28 def builtin_friendly_name(kind, which):
29 if kind is 'color':
30 return {
31 'yellow': _('Yellow highlight'),
32 'green': _('Green highlight'),
33 'blue': _('Blue highlight'),
34 'red': _('Pink highlight'),
35 'purple': _('Purple highlight'),
36 }[which] or _('Unknown highlight')
37 return {
38 'wavy': _('Red wavy underline'),
39 'strikeout': _('Red strikeout'),
40 }[which] or _('Unknown underline')
41
42
43 def builtin_color(which, is_dark):
44 return (builtin_colors_dark[which] if is_dark else builtin_colors_light[which]) or builtin_colors_light.yellow
45
46
47 def default_color(is_dark):
48 return builtin_color('yellow', is_dark)
49
50
51 def all_builtin_styles():
52 ans = []
53 for col in builtin_colors_light:
54 ans.push({'type': 'builtin', 'kind': 'color', 'which': col})
55 for which in builtin_decorations_light:
56 ans.push({'type': 'builtin', 'kind': 'decoration', 'which': which})
57 return ans
58
59 all_style_keys = v"'type kind which light dark background-color text-decoration-line text-decoration-color text-decoration-style'.split(' ')"
60
61
62 def custom_color_theme(name, lightbg, darkbg):
63 return {'type': 'custom', 'kind': 'color', 'light': lightbg, 'dark': darkbg, 'friendly_name': name}
64
65
66 def custom_decoration_theme(name, line_position, line_style, line_color):
67 return {
68 'type': 'custom', 'kind': 'decoration', 'text-decoration-line': line_position,
69 'text-decoration-style': line_style, 'text-decoration-color': line_color,
70 'friendly_name': name
71 }
72
73
74 def style_key(style):
75 return [f'{k}:{style[k]}' for k in all_style_keys].join(';')
76
77
78 class HighlightStyle:
79 def __init__(self, style):
80 if jstype(style) is 'string':
81 style = JSON.parse(style)
82 self.style = style or {'type': 'builtin', 'kind': 'color', 'which': 'yellow'}
83 self.key = style_key(self.style)
84
85 def make_swatch(self, container, is_dark):
86 style = container.style
87 style.width = style.height = style.minimumWidth = style.minimumHeight = style.maximumWidth = style.maximumHeight = ICON_SIZE
88 s = self.style
89 br = ICON_SIZE_VAL / 4
90
91 if s.kind is 'decoration':
92 tdl = tds = tdc = None
93 if s.type is 'builtin':
94 q = builtin_decorations_dark[s.which] if is_dark else builtin_decorations_dark[s.which]
95 else:
96 q = s
97 tdl = q['text-decoration-line'] or None
98 tds = q['text-decoration-style'] or None
99 tdc = q['text-decoration-color'] or None
100 container.textContent = 'ab'
101 style.paddingLeft = style.paddingRight = style.paddingTop = style.paddingBottom = '0.25ex'
102 style.borderStyle = 'solid'
103 style.borderWidth = '1px'
104 style.borderRadius = f'{br}{ICON_SIZE_UNIT}'
105 style.fontSize = 'smaller'
106 style.fontWeight = 'bold'
107 if tdl:
108 style.textDecorationLine = tdl
109 if tds:
110 style.textDecorationStyle = tds
111 if tdc:
112 style.textDecorationColor = tdc
113 return container
114
115 bg = None
116 if s.type is 'builtin':
117 bg = builtin_color(s.which, is_dark)
118 elif s.type is 'custom':
119 bg = s.dark if is_dark else s.light
120 if bg is None and s['background-color']:
121 bg = s['background-color']
122 if bg:
123 style.backgroundColor = bg
124 style.borderRadius = f'{br}{ICON_SIZE_UNIT}'
125 return container
126
127 def highlight_shade(self, is_dark):
128 s = self.style
129 if s.kind is 'decoration':
130 if s.type is 'builtin':
131 defs = builtin_decorations_dark[s.which] if is_dark else builtin_decorations_light[s.which]
132 else:
133 defs = s
134 return defs['text-decoration-color'] or 'red'
135 if s.type is 'builtin':
136 return builtin_color(s.which, is_dark)
137 if s.type is 'custom':
138 return s.dark if is_dark else s.light
139 return s['background-color'] or default_color(is_dark)
140
141 def serialized(self):
142 return JSON.stringify(self.style)
143
144 @property
145 def friendly_name(self):
146 s = self.style
147 if s.type is 'builtin':
148 return builtin_friendly_name(s.kind, s.which)
149 return s.friendly_name or _('Custom style')
150
151
152 def highlight_style_as_css(s, is_dark, foreground):
153 def styler(node):
154 def set(name, val):
155 if val:
156 node.style.setProperty(name, val, 'important')
157
158 if s.kind is 'decoration':
159 if s.type is 'builtin':
160 keys = builtin_decorations_dark[s.which] if is_dark else builtin_decorations_light[s.which]
161 else:
162 keys = s
163 set('text-decoration-line', keys['text-decoration-line'])
164 set('text-decoration-color', keys['text-decoration-color'])
165 set('text-decoration-style', keys['text-decoration-style'])
166 return
167
168 bg = None
169 fg = foreground or None
170 if s.type is 'builtin':
171 bg = builtin_color(s.which, is_dark)
172 elif s.type is 'custom':
173 bg = s.dark if is_dark else s.light
174 elif s.color:
175 fg = s.color
176 set('background-color', bg or s['background-color'] or default_color(is_dark))
177 set('color', fg or s.color or foreground)
178
179 return styler
180
181
182 def custom_styles_equal(a, b):
183 seen = {}
184 for k in a:
185 seen[k] = True
186 if a[k] is not b[k]:
187 return False
188 for k in b:
189 if not seen[k]:
190 if a[k] is not b[k]:
191 return False
192 return True
193
194
195 def all_styles():
196 ans = []
197 custom_highlight_styles = get_session_data().get('custom_highlight_styles')
198 for raw in custom_highlight_styles:
199 ans.push(HighlightStyle(raw))
200 for raw in all_builtin_styles():
201 ans.push(HighlightStyle(raw))
202 return ans
203
204
205 class AddStyle: # {{{
206 def __init__(self, get_container, hide_self):
207 self.get_container = get_container
208 self.hide_self = hide_self
209
210 def onkeydown(ev):
211 ev.stopPropagation()
212 if ev.key is 'Escape':
213 hide_self(None)
214
215 get_container().appendChild(E.div(
216 style='margin: 1rem; text-align: left',
217 E.div(_('Style name:'), ' ', E.input(name='friendly_name', onkeydown=onkeydown, placeholder=_('Name for this style'))),
218 E.div('\xa0'),
219 E.div(
220 _('Type of style:'), ' ',
221 E.label(E.input(type='radio', name='style_type', value='color', onchange=self.change_type, checked=True), _('Color')),
222 '\xa0\xa0',
223 E.label(E.input(type='radio', name='style_type', value='decoration', onchange=self.change_type), _('Underline')),
224 ),
225 E.div(
226 name='color-container',
227 style='margin-top:1rem; border-top: solid; padding-top: 1rem',
228 E.div(E.label(_('Color for light color themes: '), E.input(type='color', name='light_color', value='#ffff00'))),
229 E.div('\xa0'),
230 E.div(E.label(_('Color for dark color themes: '), E.input(type='color', name='dark_color', value='#cccc00'))),
231 ),
232 E.div(
233 name='decoration-container',
234 style='margin-top:1rem; border-top: solid; padding-top: 1rem',
235 E.div(
236 _('Color for the line: '),
237 E.label(E.input(type='radio', name='color_type', value='currentColor', checked=True), _('Text color')),
238 '\xa0',
239 E.label(E.input(type='radio', name='color_type', value='custom_color'), _('Custom color:')),
240 '\xa0',
241 E.input(type='color', name='decoration_color', value='#ff0000', onchange=def ():
242 self.get_container().querySelector('input[value=custom_color]').checked = True
243 )
244 ),
245 E.div('\xa0'),
246 E.div(
247 E.label(_('Position of line: '), E.select(name='text_decoration_line',
248 E.option(_('Underline'), value='underline'),
249 E.option(_('Over-line'), value='overline'),
250 E.option(_('Strikeout'), value='strike-through'),
251 ))
252 ),
253 E.div('\xa0'),
254 E.div(
255 E.label(_('Style of line: '), E.select(name='text_decoration_style',
256 E.option(_('Solid'), value='solid'),
257 E.option(_('Double'), value='double'),
258 E.option(_('Dotted'), value='dotted'),
259 E.option(_('Dashed'), value='dashed'),
260 E.option(_('Wavy'), value='wavy'),
261 ))
262 ),
263 ),
264 E.div(
265 style='margin-top:1rem; border-top: solid; padding-top: 1rem; display: flex; width: 100%; justify-content: space-between',
266 create_button(_('Discard'), 'close', def (ev):
267 ev.stopPropagation()
268 hide_self(None)
269 ),
270 create_button(_('Save'), 'check', def (ev):
271 ev.stopPropagation()
272 if not self.friendly_name:
273 return error_dialog(_('No name specified'), _('You must give your custom style a name'), on_close=self.focus)
274 hide_self(self.created_style)
275 ),
276 ),
277 ))
278 self.change_type()
279
280 def focus(self):
281 self.get_container().querySelector('input[name=friendly_name]').focus()
282
283 def init(self):
284 self.get_container().querySelector('input[name=friendly_name]').value = ''
285 self.focus()
286
287 @property
288 def style_type(self):
289 return self.get_container().querySelector('input[name=style_type]:checked').value
290
291 @property
292 def color_type(self):
293 return self.get_container().querySelector('input[name=color_type]:checked').value
294
295 def change_type(self):
296 c = self.get_container()
297 q = self.style_type
298 c.querySelector('[name=color-container]').style.display = 'block' if q is 'color' else 'none'
299 c.querySelector('[name=decoration-container]').style.display = 'block' if q is 'decoration' else 'none'
300
301 @property
302 def friendly_name(self):
303 return self.get_container().querySelector('input[name=friendly_name]').value
304
305 @property
306 def created_style(self):
307 c = self.get_container()
308 name = self.friendly_name
309 if self.style_type is 'color':
310 return custom_color_theme(name, c.querySelector('input[name=light_color]').value, c.querySelector('input[name=dark_color]').value)
311 if self.color_type is 'currentColor':
312 col = 'currentColor'
313 else:
314 col = c.querySelector('input[name=decoration_color]').value
315 return custom_decoration_theme(
316 name,
317 c.querySelector('select[name=text_decoration_line]').value,
318 c.querySelector('select[name=text_decoration_style]').value,
319 col)
320 # }}}
321
322
323 class EditNotesAndColors: # {{{
324 def __init__(self, container, is_dark_theme, current_notes, current_style, annot_id, close_editor):
325 self.initial_style = current_style
326 self.is_dark_theme = is_dark_theme
327 self.annot_id = annot_id
328
329 def finish():
330 close_editor(True)
331
332 def abort():
333 close_editor(False)
334
335 def handle_keypress(ev):
336 ev.stopPropagation()
337 if ev.key is 'Escape':
338 abort()
339 elif ev.key is 'Enter' and ev.ctrlKey:
340 finish()
341
342 remove_button = create_button(_('Remove style'), 'trash', self.remove_custom_color, _('Remove this custom highlight style'))
343 remove_button.classList.add('remove-custom-color')
344 apply_button = create_button(
345 _('Apply') if self.annot_id else _('Create'),
346 'check', finish,
347 (_('Finish editing highlight') if self.annot_id else _('Create highlight')) + ' [Ctrl+Enter]',
348 True
349 )
350 apply_button.style.marginLeft = apply_button.style.marginTop = 'auto'
351 stop_propagation = def (ev):
352 ev.stopPropagation()
353
354 c = E.div(
355 style=f'background: {get_color("window-background")}; margin: auto; text-align: center; padding: 1ex;',
356 onclick=stop_propagation,
357 id=unique_id(), E.div(
358 ontouchstart=stop_propagation, ontouchmove=stop_propagation, ontouchend=stop_propagation, ontouchcancel=stop_propagation,
359 oncontextmenu=stop_propagation,
360 E.textarea(
361 placeholder=_('Add notes for this highlight. Double click or long tap on a highlight to read its notes.'),
362 rows='10', spellcheck='true', style='width: 90%;',
363 onkeydown=handle_keypress,
364 ),
365 E.div(
366 class_='color-block',
367 style=f'display: flex; flex-wrap: wrap; width: 100%; justify-content: center',
368 ),
369 E.div(
370 style='width: 100%; display: flex; flex-wrap: wrap',
371 create_button(_('Cancel'), 'close', abort, _('Abort') + ' [Esc]'),
372 E.span('\xa0'),
373 remove_button, apply_button
374 ),
375 ))
376 self.container_id = c.id
377 container.appendChild(c)
378 container.style.maxWidth = '40rem'
379 container.style.width = '90%'
380 c.appendChild(E.div(style='display:none'))
381 self.add_style = AddStyle(def (): return self.container.lastChild;, self.hide_add_style)
382 self.seen_colors = {}
383 custom_highlight_styles = get_session_data().get('custom_highlight_styles')
384 for raw in custom_highlight_styles:
385 self.add_color(HighlightStyle(raw)).classList.add('custom-style')
386 for raw in all_builtin_styles():
387 self.add_color(HighlightStyle(raw))
388 if not c.querySelector('.current-swatch'):
389 self.add_color(self.initial_style, True)
390 parent = c.getElementsByClassName('color-block')[0]
391 parent.appendChild(E.div(
392 svgicon('plus', ICON_SIZE, ICON_SIZE),
393 style='padding: 4px; margin: 4px;',
394 title=_('Add a new highlight style'),
395 class_='simple-link',
396 onclick=def (ev):
397 ev.stopPropagation()
398 c = self.container
399 c.firstChild.style.display = 'none'
400 c.lastChild.style.display = 'block'
401 self.add_style.init()
402 ))
403
404 self.set_visibility_of_remove_button()
405 window.setTimeout(self.notes_edit.focus.bind(self.notes_edit), 0)
406 if current_notes:
407 self.notes_edit.value = current_notes
408
409 def hide_add_style(self, new_style):
410 c = self.container
411 c.firstChild.style.display = 'block'
412 c.lastChild.style.display = 'none'
413 if new_style:
414 self.add_new_style(new_style)
415 self.notes_edit.focus()
416
417 def add_new_style(self, new_style):
418 hs = HighlightStyle(new_style)
419 item = self.add_color(hs, True)
420 if not item:
421 # happens if the newly created style is the same as some existing
422 # style
423 for q in self.container.getElementsByClassName('swatch'):
424 if q.dataset.key is hs.key:
425 item = q
426 break
427 if item:
428 item.classList.add('custom-style')
429 self.make_swatch_current(item)
430 sd = get_session_data()
431 new_styles = [new_style]
432 seen = {hs.key: True}
433 for style in sd.get('custom_highlight_styles'):
434 hso = HighlightStyle(style)
435 if not seen[hso.key]:
436 new_styles.push(style)
437 sd.set('custom_highlight_styles', new_styles)
438
439 def set_visibility_of_remove_button(self):
440 c = self.container
441 item = c.querySelector('.current-swatch.custom-style')
442 c.querySelector('.remove-custom-color').style.display = 'flex' if item else 'none'
443
444 def add_color(self, hs, at_start):
445 if self.seen_colors[hs.key]:
446 return
447 self.seen_colors[hs.key] = True
448 ic = E.div()
449 hs.make_swatch(ic, self.is_dark_theme)
450 ic.classList.add('simple-link')
451 is_current = hs.key is self.initial_style.key
452 sqbg = get_color('window-background2') if is_current else 'unset'
453 item = E.div(
454 ic, style=f'padding: 4px; background-color: {sqbg}; margin: 4px; border-radius: {ICON_SIZE_VAL/4}{ICON_SIZE_UNIT}',
455 onclick=self.change_color, title=hs.friendly_name
456 )
457 if is_current:
458 item.classList.add('current-swatch')
459 item.classList.add('swatch')
460 item.dataset.style = hs.serialized()
461 item.dataset.key = hs.key
462 parent = self.container.getElementsByClassName('color-block')[0]
463 if at_start:
464 parent.insertBefore(item, parent.firstChild)
465 else:
466 parent.appendChild(item)
467 return item
468
469 def remove_custom_color(self):
470 question_dialog(_('Are you sure?'), _(
471 'Do you want to permanently delete this highlighting style?'), def (yes):
472 if yes:
473 self.do_remove_custom_color()
474 )
475
476 def do_remove_custom_color(self):
477 item = self.container.getElementsByClassName('current-swatch')[0]
478 cct = JSON.parse(item.dataset.style)
479 p = item.parentNode
480 p.removeChild(item)
481 self.make_swatch_current(p.firstChild)
482 sd = get_session_data()
483 custom_highlight_styles = sd.get('custom_highlight_styles')
484 ans = []
485 for x in custom_highlight_styles:
486 if not custom_styles_equal(x, cct):
487 ans.push(x)
488 sd.set('custom_highlight_styles', ans)
489
490 @property
491 def container(self):
492 return document.getElementById(self.container_id)
493
494 @property
495 def notes_edit(self):
496 return self.container.getElementsByTagName('textarea')[0]
497
498 def change_color(self, evt):
499 evt.stopPropagation()
500 self.make_swatch_current(evt.currentTarget)
501
502 def make_swatch_current(self, item):
503 for child in item.parentNode.childNodes:
504 child.style.backgroundColor = 'unset'
505 child.classList.remove('current-swatch')
506 item.style.backgroundColor = get_color('window-background2')
507 item.classList.add('current-swatch')
508 self.notes_edit.focus()
509 self.set_visibility_of_remove_button()
510
511 @property
512 def current_notes(self):
513 return self.notes_edit.value or ''
514
515 @property
516 def current_style(self):
517 style = self.container.getElementsByClassName('current-swatch')[0].dataset.style
518 return HighlightStyle(JSON.parse(style))
519 # }}}
520
521
522 # Browse highlights panel {{{
523
524
525 def get_container_id():
526 if not get_container_id.ans:
527 get_container_id.ans = unique_id()
528 return get_container_id.ans
529
530
531 def get_container():
532 return document.getElementById(get_container_id())
533
534
535 def get_current_link_prefix():
536 if runtime.is_standalone_viewer:
537 return current_book().calibre_book_url
538 link_prefix = window.location.href
539 return link_prefix[:link_prefix.indexOf('#') + 1]
540
541
542 def link_to_epubcfi(epubcfi, link_prefix, current_query):
543 if runtime.is_standalone_viewer:
544 current_query = {'open_at': epubcfi}
545 link = encode_query(current_query)
546 else:
547 if not current_query:
548 current_query = Object.assign({}, get_current_query())
549 current_query.bookpos = epubcfi
550 link = encode_query(current_query)[1:]
551 return link_prefix + link.replace(/\)/g, '%29').replace(/\(/g, '%28')
552
553
554 def render_highlight_as_text(hl, lines, link_prefix, current_query, as_markdown=False):
555 lines.push(hl.highlighted_text)
556 date = Date(hl.timestamp).toLocaleString()
557 if as_markdown:
558 cfi = hl.start_cfi
559 spine_index = (1 + hl.spine_index) * 2
560 link = link_to_epubcfi(f'epubcfi(/{spine_index}{cfi})', link_prefix, current_query)
561 date = f'[{date}]({link})'
562 lines.push(date)
563 notes = hl.notes
564 if notes:
565 lines.push('')
566 lines.push(notes)
567 lines.push('')
568 if as_markdown:
569 lines.push('-' * 20)
570 else:
571 lines.push('───')
572 lines.push('')
573
574
575 class ChapterGroup:
576 def __init__(self, title, level):
577 self.level = level or 0
578 self.title = title or ''
579 self.subgroups = v'{}'
580 self.subgroups_in_order = []
581 self.annotations = []
582
583 def add_annot(self, a):
584 titles = a['toc_family_titles']
585 if not titles:
586 titles = [_('Unknown chapter')]
587 node = self
588 for title in titles:
589 node = node.group_for_title(title)
590 node.annotations.push(a)
591
592 def group_for_title(self, title):
593 ans = self.subgroups[title]
594 if not ans:
595 ans = ChapterGroup(title, self.level + 1)
596 self.subgroups[title] = ans
597 self.subgroups_in_order.push(title)
598 return ans
599
600 def render_as_text(self, lines, link_prefix, current_query, as_markdown):
601 if self.title:
602 lines.push('#' * self.level + ' ' + self.title)
603 lines.push('')
604 for hl in self.annotations:
605 render_highlight_as_text(hl, lines, link_prefix, current_query, as_markdown)
606 for title in self.subgroups_in_order:
607 sg = self.subgroups[title]
608 sg.render_as_text(lines, link_prefix, current_query, as_markdown)
609
610
611 def show_export_dialog(annotations_manager, book_metadata):
612 sd = get_session_data()
613 fmt = sd.get('highlights_export_format')
614 if ['text', 'markdown', 'calibre_annotations_collection'].indexOf(fmt) < 0:
615 fmt = 'text'
616 all_highlights = annotations_manager.all_highlights()
617 selected_highlight_items = all_selected_entries()
618 if selected_highlight_items.length:
619 key = {e.dataset.uuid: True for e in selected_highlight_items}
620 all_highlights = [h for h in all_highlights if key[h.uuid]]
621 ta_id = unique_id()
622 href = window.location.href
623 idx = href.indexOf('#')
624 href = href[:idx + 1]
625 current_query = Object.assign({}, get_current_query())
626 link_prefix = get_current_link_prefix()
627
628 def update_text():
629 if fmt is 'calibre_annotations_collection':
630 data = {
631 'version': 1,
632 'type': 'calibre_annotation_collection',
633 'annotations': all_highlights,
634 }
635 document.getElementById(ta_id).textContent = JSON.stringify(data, None, 2)
636 return
637 as_markdown = fmt is 'markdown'
638 lines = []
639 root = ChapterGroup()
640 for a in all_highlights:
641 root.add_annot(a)
642 root.render_as_text(lines, link_prefix, current_query, as_markdown)
643 document.getElementById(ta_id).textContent = lines.join('\n')
644
645 def fmt_item(text, val):
646 ans = E.label(E.input(type='radio', name='format', value=val, checked=val is fmt), '\xa0', text)
647 ans.style.marginRight = '1rem'
648 ans.firstChild.addEventListener('change', def (ev):
649 nonlocal fmt
650 fmt = this.value
651 sd.set('highlights_export_format', this.value)
652 update_text()
653 )
654 return ans
655
656 create_custom_dialog(_('Export highlights'), def (modal_container, close_modal):
657 modal_container.appendChild(E.div(
658 E.div(_('Format for exported highlights:')),
659 E.div(
660 fmt_item(_('Plain text'), 'text'),
661 fmt_item(_('Markdown'), 'markdown'),
662 fmt_item('calibre', 'calibre_annotations_collection'),
663 ),
664 E.textarea(style='margin-top: 1ex; resize: none; max-height: 25vh', readonly=True, rows='20', cols='80', id=ta_id),
665 E.div(
666 class_='button-box',
667 create_button(_('Copy'), 'copy', def (ev):
668 x = document.getElementById(ta_id)
669 x.focus()
670 x.select()
671 document.execCommand('copy')
672 ),
673 create_button(_('Download'), 'cloud-download', def (ev):
674 nonlocal fmt
675 text = document.getElementById(ta_id).textContent
676 ext = 'md' if fmt is 'markdown' else ('txt' if fmt is 'text' else 'json')
677 mt = 'text/markdown' if fmt is 'markdown' else ('text/plain' if fmt is 'text' else 'application/json')
678 title = book_metadata?.title or _('Unknown')
679 filename = _('{title} - highlights').format(title=title) + f'.{ext}'
680 file = new Blob([text], {'type': mt})
681 url = window.URL.createObjectURL(file)
682 a = E.a(href=url, download=filename)
683 document.body.appendChild(a)
684 a.click()
685 window.setTimeout(def ():
686 document.body.removeChild(a)
687 window.URL.revokeObjectURL(url)
688 , 0)
689 ),
690 )
691 ))
692 window.setTimeout(update_text, 0)
693 )
694
695
696 def focus_search():
697 c = get_container()
698 c.querySelector('input').focus()
699
700
701 def find(backwards):
702 c = get_container()
703 text = c.querySelector('input').value
704 if not text:
705 return False
706 all_highlights = list(c.querySelectorAll('.highlight')).as_array()
707 current = c.querySelector('.highlight.current')
708 if current:
709 start = all_highlights.indexOf(current)
710 if backwards:
711 all_highlights = all_highlights[:start].reverse().concat(all_highlights[start:].reverse())
712 else:
713 all_highlights = all_highlights[start + 1:].concat(all_highlights[:start + 1])
714 elif backwards:
715 all_highlights.reverse()
716 q = text.toLowerCase()
717 for h in all_highlights:
718 if h.dataset.title.toLowerCase().indexOf(q) > -1 or h.dataset.notes.toLowerCase().indexOf(q) > -1:
719 set_current_highlight_entry(h)
720 h.scrollIntoView()
721 if h is current:
722 warning_dialog(_('Not found'), _('No other matches found for: {}').format(text), on_close=focus_search)
723 return True
724 warning_dialog(_('Not found'), _('No matches found for: {}').format(text), on_close=focus_search)
725 return False
726
727
728 def find_previous():
729 return find(True)
730
731
732 def find_next():
733 return find(False)
734
735
736 add_extra_css(def ():
737 ans = ''
738 sel = '#' + get_container_id()
739 ans += build_rule(sel + ' .ac-button', margin_left='1rem', margin_top='1ex')
740 ans += build_rule(sel + ' .sel-button', display='none')
741 sel += ' .toc-group'
742 ans += build_rule(sel + ' h3', display='flex', align_items='center', cursor='pointer', margin_top='1ex')
743 ans += build_rule(sel + '.expanded .caret-right', display='none')
744 ans += build_rule(sel + '.collapsed .caret-down', display='none')
745 ans += build_rule(sel + '.collapsed > div', display='none')
746 qsel = sel + ' .highlight'
747 ans += build_rule(qsel, margin_top='1ex', border_top='solid 1px', padding_top='1ex', cursor='pointer')
748 ans += build_rule(qsel + ' .notes', display='none', margin_top='1ex', max_height='20ex', overflow='auto')
749 ans += build_rule(qsel + ' .actions', display='none', margin_top='1ex', justify_content='space-between', flex_wrap='wrap', gap='0.65rem')
750 ans += build_rule(qsel + ' .title', display='flex', align_items='center')
751 ans += build_rule(qsel + ' .title-row', display='flex', align_items='center', justify_content='space-between')
752 current = qsel + '.current'
753 ans += build_rule(current + ' .title', font_weight='bold', font_size='larger')
754 ans += build_rule(current + ' .notes', display='block')
755 ans += build_rule(current + ' .actions', display='flex')
756 return ans
757 )
758
759 url_pat = /\bhttps?:\/\/\S{3,}/ig
760 closing_bracket_map = {'(': ')', '[': ']', '{': '}', '<': '>', '*': '*', '"': '"', "'": "'"}
761 opening_brackets = Object.keys(closing_bracket_map).join('')
762
763
764 def url(text: str, s: int, e: int):
765 while '.,?!'.indexOf(text[e - 1]) > -1 and e > 1: # remove trailing punctuation
766 e -= 1
767 # truncate url at closing bracket/quote
768 if s > 0 and e <= text.length and closing_bracket_map[text[s - 1]]:
769 q = closing_bracket_map[text[s - 1]]
770 idx = text.indexOf(q, s)
771 if idx > s:
772 e = idx
773 return s, e
774
775
776 def render_notes(notes, container, make_urls_clickable):
777 current_para = E.p()
778
779 def add_para():
780 nonlocal current_para
781 container.appendChild(current_para)
782 if container.childNodes.length > 1:
783 container.lastChild.style.marginTop = '2ex'
784 current_para = E.p()
785
786 def add_line(line):
787 url_pat.lastIndex = 0
788 urls = []
789
790 while make_urls_clickable:
791 m = url_pat.exec(line)
792 if not m:
793 break
794 urls.push(url(line, m.index, url_pat.lastIndex))
795 if not urls.length:
796 current_para.appendChild(document.createTextNode(line))
797 return
798 pos = 0
799 for (s, e) in urls:
800 if s > pos:
801 current_para.appendChild(document.createTextNode(line[pos:s]))
802 current_para.appendChild(E.a(line[s:e], href='javascript: void(0)', class_='blue-link', onclick=ui_operations.open_url.bind(None, line[s:e])))
803 if urls[-1][1] < line.length:
804 current_para.appendChild(document.createTextNode(line[urls[-1][1]:]))
805
806 for line in notes.splitlines():
807 if not line or not line.strip():
808 if current_para.childNodes.length:
809 add_para()
810 continue
811 add_line(line)
812 if current_para.childNodes.length:
813 add_para()
814 return container
815
816
817 def highlight_entry_clicked(ev):
818 set_current_highlight_entry(ev.currentTarget)
819
820
821 def set_current_highlight_entry(entry):
822 c = get_container()
823 for h in c.querySelectorAll('.highlight'):
824 h.classList.remove('current')
825 entry.classList.add('current')
826
827
828 def show_in_text(annot_id, view):
829 view.highlight_action(annot_id, 'goto')
830
831
832 def remove_highlight(annot_id, view, ev):
833 entry = ev.currentTarget.closest('.highlight')
834 question_dialog(_('Are you sure?'), _(
835 'Do you want to permanently delete this highlight?'), def (yes):
836 if yes:
837 entry.style.display = 'none'
838 view.highlight_action(annot_id, 'delete')
839 )
840
841
842 def edit_notes(annot_id, notes, view, ev):
843 entry = ev.currentTarget.closest('.highlight')
844 get_text_dialog(_('Notes'), def (ok, text):
845 if not ok:
846 return
847 text = text or ''
848 nc = entry.querySelector('.notes')
849 clear(nc)
850 view.set_notes_for_highlight(annot_id, text)
851 render_notes(text, nc)
852 , initial_text = notes or None)
853
854
855 def all_selected_entries():
856 return [e.closest('.highlight') for e in document.querySelectorAll('.highlight input:checked')]
857
858
859 def item_select_toggled():
860 entries = all_selected_entries()
861 for e in document.querySelectorAll(f'#{get_container_id()} .sel-button'):
862 e.style.display = 'inline-flex' if entries.length else 'none'
863
864
865 def clear_selection():
866 for e in document.querySelectorAll('.highlight input:checked'):
867 e.checked = False
868 item_select_toggled()
869
870
871 def select_all():
872 for e in document.querySelectorAll('.highlight input'):
873 e.checked = True
874
875
876 def delete_selection(annotations_manager, view):
877 selected_highlight_items = all_selected_entries()
878 if not selected_highlight_items.length:
879 return
880 text = ngettext(
881 'Do you want to permanently delete the selected highlight?',
882 'Do you want to permanently delete the {} selected highlights?',
883 selected_highlight_items.length
884 ).format(selected_highlight_items.length)
885 question_dialog(_('Are you sure?'), text, def (yes):
886 if yes:
887 for entry in selected_highlight_items:
888 entry.style.display = 'none'
889 view.highlight_action(entry.dataset.uuid, 'delete')
890 )
891
892
893 def highlight_entry(h, onclick, view, hide_panel):
894 def action(func, ev):
895 ev.stopPropagation(), ev.preventDefault()
896 onclick(func)
897
898 hs = HighlightStyle(h.style)
899 swatch = E.div()
900 hs.make_swatch(swatch, is_dark_theme())
901 ans = E.div(
902 class_='highlight',
903 data_uuid=h.uuid,
904 onclick=highlight_entry_clicked,
905 E.div(
906 class_='title-row',
907 E.div(class_='title', swatch, E.div(style='margin-left: 1rem', h.highlighted_text)),
908 E.div(style='margin-left: 1rem', onclick=def (ev): ev.stopPropagation();,
909 E.input(type='checkbox', onchange=item_select_toggled, onkeydown=def (ev):
910 if ev.key is 'Escape':
911 ev.stopPropagation()
912 ev.preventDefault()
913 hide_panel()
914 )),
915 ),
916 E.div(
917 class_='actions',
918 create_button(_('Show in book'), 'book', action.bind(None, show_in_text.bind(None, h.uuid))),
919 E.span('\xa0'),
920 create_button(_('Edit notes'), 'edit', edit_notes.bind(None, h.uuid, h.notes, view)),
921 E.span('\xa0'),
922 create_button(_('Remove highlight'), 'trash', remove_highlight.bind(None, h.uuid, view)),
923 ),
924 E.div(class_='notes')
925 )
926 if h.notes:
927 render_notes(h.notes, ans.querySelector('.notes'), True)
928 ans.dataset.notes = h.notes or ''
929 ans.dataset.title = h.highlighted_text or ''
930 return ans
931
932
933 def create_icon_button(icon, title, action):
934 return E.a(svgicon(icon), class_='calibre-icon-button ac-button', title=title, onclick=def (ev):
935 ev.preventDefault()
936 action()
937 , onmousedown = def (e): e.preventDefault();)
938
939
940 def create_highlights_panel(annotations_manager, hide_panel, book, container, onclick):
941 next_button = create_icon_button('chevron-down', _('Next match'), find_next)
942 prev_button = create_icon_button('chevron-up', _('Previous match'), find_previous)
943 sb = create_search_bar(find_next, 'search-in-highlights', placeholder=_('Search') + '…', button=next_button, associated_widgets=[prev_button])
944 sb.style.flexGrow = '10'
945 sb.classList.add('ac-button')
946 clear_button = create_button(
947 _('Clear'), 'close', clear_selection, _('Clear selection'), class_='ac-button sel-button')
948 delete_button = create_button(
949 _('Remove'), 'trash', delete_selection.bind(None, annotations_manager, annotations_manager.view), _('Remove selected highlights'),
950 class_='ac-button sel-button')
951 all_button = create_button(
952 _('All'), 'plus', select_all, _('Select all highlights'),
953 class_='ac-button sel-button')
954 export_button = create_button(
955 _('Export'), 'cloud-download', show_export_dialog.bind(None, annotations_manager, book.metadata), _('Export all or selected highlights'),
956 class_='ac-button')
957 c = E.div(
958 style='padding: 1rem',
959 id=get_container_id(),
960 E.div(
961 style='display: flex; flex-wrap: wrap; margin-top: -1ex; align-items: center',
962 sb, next_button, prev_button, clear_button, all_button, delete_button, export_button
963 ),
964 )
965 container.appendChild(c)
966 toc_groups = {}
967 toc_tt = {}
968 for h in annotations_manager.all_highlights():
969 toc = _('Unknown')
970 if h.toc_family_titles?.length:
971 toc = h.toc_family_titles[-1]
972 if not toc_groups[toc]:
973 toc_groups[toc] = []
974 if h.toc_family_titles?.length:
975 lines = []
976 for i, node in enumerate(h.toc_family_titles):
977 lines.push('\xa0\xa0' * i + '➤ ' + node)
978 tt = ngettext('Table of Contents section:', 'Table of Contents sections:', lines.length)
979 tt += '\n' + '\n'.join(lines)
980 toc_tt[toc] = tt
981 toc_groups[toc].push(h)
982
983 def tree_icon(which):
984 ans = svgicon(which)
985 ans.classList.add(which)
986 return ans
987
988 for group in Object.keys(toc_groups):
989 highlights = toc_groups[group]
990 g = E.div(
991 class_='toc-group expanded',
992 E.h3(
993 title=toc_tt[group] or '',
994 tree_icon('caret-right'), tree_icon('caret-down'), E.div('\xa0' + group),
995 onclick=def (ev):
996 tg = ev.currentTarget.closest('.toc-group')
997 if tg.classList.contains('expanded'):
998 tg.classList.remove('expanded')
999 tg.classList.add('collapsed')
1000 else:
1001 tg.classList.remove('collapsed')
1002 tg.classList.add('expanded')
1003 ),
1004 E.div(style='margin-left: 1rem')
1005 )
1006 c.appendChild(g)
1007 ic = g.lastChild
1008 for h in highlights:
1009 ic.appendChild(highlight_entry(h, onclick, annotations_manager.view, hide_panel))
1010 # }}}