Debian Codegraph @

src/pyj/book_list/edit_metadata.pyj

raw
1 # vim:fileencoding=utf-8
2 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
3 from __python__ import bound_methods, hash_literals
4
5 import traceback
6 from elementmaker import E
7 from gettext import gettext as _
8
9 from ajax import ajax_send
10 from book_list.book_details import (
11 add_stars_to, basic_table_rules, fetch_metadata, field_sorter, no_book,
12 report_load_failure
13 )
14 from book_list.comments_editor import (
15 create_comments_editor, focus_comments_editor, get_comments_html, set_comments_html
16 )
17 from book_list.globals import get_current_query, book_whose_metadata_is_being_edited
18 from book_list.library_data import (
19 book_metadata, cover_url, current_library_id, field_names_for, library_data,
20 load_status, loaded_book_ids, set_book_metadata
21 )
22 from book_list.router import back, push_state, show_note
23 from book_list.theme import get_color
24 from book_list.top_bar import create_top_bar, set_title
25 from book_list.ui import set_panel_handler, show_panel
26 from date import UNDEFINED_DATE_ISO, format_date
27 from dom import add_extra_css, build_rule, clear, svgicon
28 from file_uploads import update_status_widget, upload_files_widget, upload_status_widget
29 from modals import error_dialog, question_dialog
30 from session import get_interface_data
31 from utils import conditional_timeout, fmt_sidx, parse_url_params, safe_set_inner_html
32 from widgets import create_button
33
34 CLASS_NAME = 'edit-metadata-panel'
35 IGNORED_FIELDS = {
36 'sort',
37 'uuid',
38 'id',
39 'urls_from_identifiers',
40 'lang_names',
41 'last_modified',
42 'path',
43 'marked',
44 'size',
45 'ondevice',
46 'cover',
47 'au_map',
48 'isbn',
49 'in_tag_browser',
50 }
51
52
53 def identity(x):
54 return x
55 value_to_json = identity
56 changes = {}
57 draft_changes = {}
58 has_changes = False
59
60 add_extra_css(def ():
61 sel = '.' + CLASS_NAME + ' '
62 style = basic_table_rules(sel)
63 style += build_rule(sel + 'table.metadata', width='100%')
64 style += build_rule(sel + 'table.metadata td',
65 padding_top='0.65rem', padding_bottom='0.65rem',
66 padding_left='0.75rem', padding_right='0.75rem',
67 cursor='pointer',
68 border_bottom='var(--calibre-border-style-subtle)'
69 )
70 style += build_rule(sel + 'table.metadata td:first-of-type', font_weight='600')
71 style += build_rule(sel + 'table.metadata tr:hover td', background_color='var(--calibre-color-primary-light)')
72 style += build_rule(sel + 'table.metadata tr:active td', transform='translateY(0.5px)')
73 style += build_rule(sel + '.completions', display='flex', flex_wrap='wrap', align_items='center', margin_bottom='0.5ex', gap='0.4rem')
74 style += build_rule(sel + '.completions > div',
75 margin='0',
76 padding='0.45ex 0.75rem',
77 border='var(--calibre-border-style-subtle)',
78 border_radius='999px',
79 cursor='pointer',
80 user_select='none'
81 )
82 style += build_rule(sel + '.completions > div:hover',
83 background_color='var(--calibre-color-primary-light)',
84 border='var(--calibre-border-style)'
85 )
86 style += build_rule(sel + '.rating-edit-container', display='flex', flex_wrap='wrap', align_items='center', list_style_type='none')
87 style += build_rule(
88 sel + '.rating-edit-container > li',
89 margin='0.5ex 0.5rem', margin_left='0', padding='0.5ex 0.5rem',
90 border='solid 1px currentColor', border_radius='1ex', cursor='pointer'
91 )
92 style += build_rule(sel + '.rating-edit-container > li.current-rating', color=get_color('window-background'), background=get_color('window-foreground'))
93 # Floating editor modal (field editing)
94 style += build_rule(sel + 'div[data-ctype="edit"]',
95 position='fixed',
96 left='50%',
97 top='10vh',
98 transform='translateX(-50%)',
99 width='min(980px, calc(100% - 2rem))',
100 max_height='80vh',
101 overflow='auto',
102 z_index='1001',
103 background_color=get_color('window-background'),
104 border='var(--calibre-border-style-subtle)',
105 border_radius='16px',
106 box_shadow='0 24px 64px rgba(0,0,0,0.18)',
107 padding='1rem'
108 )
109 # Modal content styling: align with overall theme
110 style += build_rule(sel + 'div[data-ctype="edit"] h3',
111 margin='0 0 0.75rem 0',
112 font_weight='800'
113 )
114 style += build_rule(sel + 'div[data-ctype="edit"] .metadata-editor',
115 width='100%',
116 box_sizing='border-box'
117 )
118 style += build_rule(
119 sel + 'div[data-ctype="edit"] input[type="text"], ' +
120 sel + 'div[data-ctype="edit"] input[type="number"], ' +
121 sel + 'div[data-ctype="edit"] textarea, ' +
122 sel + 'div[data-ctype="edit"] select',
123 width='100%',
124 box_sizing='border-box',
125 padding='0.6rem 0.75rem',
126 border_radius='12px',
127 border='var(--calibre-border-style-subtle)',
128 background_color='rgba(0,0,0,0.02)'
129 )
130 style += build_rule(sel + 'div[data-ctype="edit"] textarea',
131 min_height='10rem',
132 resize='vertical'
133 )
134 style += build_rule(sel + 'div[data-ctype="edit"] .edit-form-button-container',
135 display='flex',
136 justify_content='flex-end',
137 margin_top='0.75rem'
138 )
139 style += build_rule(sel + 'div[data-ctype="edit"] .cover-edit-layout',
140 display='flex',
141 flex_direction='column',
142 gap='0.85rem'
143 )
144 style += build_rule(sel + 'div[data-ctype="edit"] .cover-edit-preview',
145 width='min(260px, 45vw)',
146 aspect_ratio='2 / 3',
147 border_radius='14px',
148 overflow='hidden',
149 border='var(--calibre-border-style-subtle)',
150 background='rgba(0,0,0,0.04)',
151 box_shadow='0 10px 24px rgba(0,0,0,0.12)'
152 )
153 style += build_rule(sel + 'div[data-ctype="edit"] .cover-edit-preview img',
154 width='100%',
155 height='100%',
156 display='block',
157 object_fit='cover'
158 )
159 style += build_rule(sel + 'div[data-ctype="edit"] .cover-edit-help',
160 opacity='0.78',
161 font_weight='700'
162 )
163 style += build_rule(sel + 'div[data-ctype="edit"] .cover-edit-actions',
164 display='flex',
165 gap='0.6rem',
166 flex_wrap='wrap'
167 )
168 style += build_rule(sel + 'div[data-ctype="edit"] .cover-edit-layout .cs-upload-dropzone',
169 display='flex',
170 flex_direction='column',
171 align_items='center',
172 gap='0.75rem',
173 padding='0.75rem',
174 cursor='pointer',
175 border='2px dashed var(--calibre-color-border)',
176 min_height='0',
177 )
178 style += build_rule(sel + 'div[data-ctype="edit"] .cover-edit-layout .cs-upload-dropzone:hover',
179 background_color='var(--calibre-color-primary-light-2)',
180 border_color='var(--calibre-color-primary)',
181 )
182 style += build_rule(sel + '[data-modal="1"] div[data-ctype="show"]',
183 opacity='0.5',
184 pointer_events='none',
185 filter='blur(1px)'
186 )
187 style += r'''
188 edit-metadata-panel[data-modal="1"]::before{
189 content:"";
190 position:fixed;
191 inset:0;
192 background:rgba(0,0,0,0.35);
193 z-index:1000;
194 }
195 '''
196 style += build_rule(sel + ' .edit-metadata-footer',
197 display='flex',
198 align_items='center',
199 justify_content='center',
200 gap='0.75rem',
201 flex_wrap='wrap',
202 padding='0 1rem 1.5rem 1rem'
203 )
204 return style
205 )
206
207
208 def resolved_metadata(mi, field):
209 if Object.prototype.hasOwnProperty.call(draft_changes, field):
210 return draft_changes[field]
211 return mi[field]
212
213
214 def resolved_formats(val):
215 val = list(val or [])
216 if draft_changes.added_formats:
217 for data in draft_changes.added_formats:
218 ext = data.ext.toUpperCase()
219 if ext and ext not in val:
220 val.push(ext)
221 if draft_changes.removed_formats:
222 for fmt in draft_changes.removed_formats:
223 fmt = fmt.toUpperCase()
224 if fmt in val:
225 val.remove(fmt)
226 val.sort()
227 return val
228
229
230 def truncated_html(val):
231 ans = val.replace(/<[^>]+>/g, '')
232 if ans.length > 40:
233 ans = ans[:40] + '…'
234 return ans
235
236
237 def onsubmit_field2(container_id, book_id, field, value):
238 nonlocal has_changes, draft_changes
239 c = document.getElementById(container_id)
240 if not c:
241 return
242 d = c.querySelector('div[data-ctype="edit"]')
243 if not d:
244 return
245 is_series = value.series_index is not undefined
246 if is_series:
247 unchanged = value.series_name is book_metadata(book_id)[field] and value.series_index is book_metadata(book_id)[field + '_index']
248 else:
249 unchanged = value is book_metadata(book_id)[field]
250 if unchanged:
251 on_close(container_id)
252 return
253
254 if is_series:
255 draft_changes[field] = value_to_json(value.series_name)
256 draft_changes[field + '_index'] = float(value.series_index)
257 else:
258 draft_changes[field] = value_to_json(value)
259 has_changes = True
260 on_close(container_id)
261
262
263 def onsubmit_field(get_value, container_id, book_id, field):
264 c = document.getElementById(container_id)
265 if not c:
266 return
267 d = c.querySelector('div[data-ctype="edit"]')
268 if not d:
269 return
270 if get_value is html_edit_get_value:
271 html_edit_get_value(d, onsubmit_field2.bind(None, container_id, book_id, field))
272 else:
273 ok, value = get_value(d)
274 if not ok:
275 return
276 # needed to avoid console error about form submission failing because form is removed from DOM in onsubmit handler
277 window.setTimeout(onsubmit_field2, 0, container_id, book_id, field, value)
278
279
280 def create_form(widget, get_value, container_id, book_id, field):
281 submit_action = onsubmit_field.bind(None, get_value, container_id, book_id, field)
282 button = create_button(_('OK'), icon='check', action=submit_action, highlight=True)
283 cancel_button = create_button(_('Cancel'), icon='close', action=def (ev): on_close(container_id);)
284 widget.classList.add('metadata-editor')
285 form = E.form(
286 action='javascript: void(0)', onsubmit=submit_action, style='margin: 1ex auto',
287 E.div(widget, style='margin-bottom: 1ex'),
288 E.div(class_='edit-form-button-container', cancel_button, '\xa0', button), E.input(type='submit', style='display:none'),
289 )
290 return form
291
292
293 # Simple line edit {{{
294
295
296 def line_edit_get_value(container):
297 return True, container.querySelector('input[type="text"]').value
298
299
300 def simple_line_edit(container_id, book_id, field, fm, div, mi):
301 nonlocal value_to_json
302 name = fm.name or field
303 le = E.input(type='text', name=name.replace('#', '_c_'), autocomplete=True, style='width: 100%')
304 le.value = resolved_metadata(mi, field) or ''
305 form = create_form(le, line_edit_get_value, container_id, book_id, field)
306 div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Edit the "{}" below').format(name)))
307 div.appendChild(E.div(style='margin: 0.5ex 1rem', form))
308 le.focus(), le.select()
309 value_to_json = identity
310 # }}}
311
312 # Text edit {{{
313
314
315 def text_edit_get_value(container):
316 return True, container.querySelector('textarea').value
317
318
319 def text_edit(container_id, book_id, field, fm, div, mi, get_name):
320 nonlocal value_to_json
321 name = fm.name or field
322 le = E.textarea(name=name.replace('#', '_c_'), spellcheck='true', wrap='soft', style='width: 100%; min-height: 70vh')
323 le.value = resolved_metadata(mi, get_name or field) or ''
324 form = create_form(le, text_edit_get_value, container_id, book_id, field)
325 div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Edit the "{}" below').format(name)))
326 div.appendChild(E.div(style='margin: 0.5ex 1rem', form))
327 le.focus()
328
329
330 def html_edit_get_value(container, proceed):
331 get_comments_html(container, def (html, data):
332 proceed(html)
333 )
334
335
336 def html_edit(container_id, book_id, field, fm, div, mi):
337 nonlocal value_to_json
338 value_to_json = identity
339 val = resolved_metadata(mi, field) or ''
340 name = fm.name or field
341 c = E.div(style='width: 100%; min-height: 75vh')
342 form = create_form(c, html_edit_get_value, container_id, book_id, field)
343 editor = create_comments_editor(c)
344 set_comments_html(c, val)
345 div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Edit the "{}" below').format(name)))
346 div.appendChild(E.div(style='margin: 0.5ex 1rem', form))
347 focus_comments_editor(c)
348 value_to_json = identity
349 editor.init()
350 # }}}
351
352 # Number edit {{{
353
354
355 def number_edit_get_value(container):
356 return True, container.querySelector('input[type="number"]').value
357
358
359 def number_edit(container_id, book_id, field, fm, div, mi):
360 nonlocal value_to_json
361 name = fm.name or field
362 le = E.input(type='number', name=name.replace('#', '_c_'), step='any' if fm.datatype is 'float' else '1')
363 val = resolved_metadata(mi, field)
364 if val?:
365 le.value = val
366 else:
367 le.value = ''
368 form = create_form(le, number_edit_get_value, container_id, book_id, field)
369 div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Edit the "{}" below').format(name)))
370 div.appendChild(E.div(style='margin: 0.5ex 1rem', form))
371 le.focus(), le.select()
372
373 def safe_parse(x):
374 f = parseFloat if fm.datatype is 'float' else parseInt
375 ans = f(x)
376 if isNaN(ans):
377 ans = None
378 return ans
379 value_to_json = safe_parse
380 # }}}
381
382 # Line edit with completions {{{
383
384
385 def remove_item(container_id, name):
386 c = document.getElementById(container_id)
387 if not c:
388 return
389 le = c.querySelector('[data-ctype="edit"] input')
390 val = le.value or ''
391 val = value_to_json(val)
392 val = [x for x in val if x is not name]
393 le.value = val.join(update_completions.list_to_ui)
394 le.focus()
395 line_edit_updated(container_id, le.dataset.field)
396
397
398 def add_completion(container_id, name):
399 c = document.getElementById(container_id)
400 if not c:
401 return
402 le = c.querySelector('[data-ctype="edit"] input')
403 val = le.value or ''
404 val = value_to_json(val)
405 if jstype(val) is 'string':
406 le.value = name
407 elif val:
408 if val.length:
409 val[-1] = name
410 else:
411 val.push(name)
412 le.value = val.join(update_completions.list_to_ui) + update_completions.list_to_ui
413 le.focus()
414 line_edit_updated(container_id, le.dataset.field)
415
416
417 def show_completions(container_id, div, field, prefix, names):
418 clear(div)
419 completions = E.div(class_='completions')
420 if names.length:
421 div.appendChild(E.div(_('Tap to add:')))
422 div.appendChild(completions)
423 for i, name in enumerate(names):
424 completions.appendChild(E.div(E.span(style='color: green', svgicon('plus'), '\xa0'), name, onclick=add_completion.bind(None, container_id, name)))
425 if i >= 50:
426 break
427
428
429 def query_contains(haystack, needle):
430 return haystack.toLowerCase().indexOf(needle) is not -1
431
432
433 def query_startswith(haystack, needle):
434 return haystack.toLowerCase().startsWith(needle)
435
436
437 def query_startswith_hierarchical(haystack, needle):
438 haystack = haystack.toLowerCase()
439 return haystack.startsWith(needle) or haystack.indexOf('.' + needle) is not -1
440
441
442 def update_removals(container_id):
443 c = document.getElementById(container_id)
444 if not c:
445 return
446 d = c.querySelector('div[data-ctype="edit"]')
447 if not d or d.style.display is not 'block':
448 return
449 div = d.lastChild.previousSibling
450 clear(div)
451 val = d.querySelector('input')?.value or ''
452 val = value_to_json(val)
453 if jstype(val) is 'string' or not val.length:
454 return
455 div.appendChild(E.div(_('Tap to remove:')))
456 removals = E.div(class_='completions')
457 div.appendChild(removals)
458 for i, name in enumerate(val):
459 removals.appendChild(E.div(
460 E.span(style='color: ' + get_color('window-error-foreground'), svgicon('eraser'), '\xa0'),
461 name, onclick=remove_item.bind(None, container_id, name)
462 ))
463 if i >= 50:
464 break
465
466
467 def update_completions(container_id, ok, field, names):
468 c = document.getElementById(container_id)
469 if not c:
470 return
471 d = c.querySelector('div[data-ctype="edit"]')
472 if not d or d.style.display is not 'block':
473 return
474 div = d.lastChild
475 clear(div)
476 if not ok:
477 err = E.div()
478 safe_set_inner_html(err, names)
479 div.appendChild(E.div(
480 _('Failed to download items for completion, with error:'), err
481 ))
482 return
483 val = d.querySelector('input').value or ''
484 val = value_to_json(val)
485 if jstype(val) is 'string':
486 prefix = val
487 else:
488 prefix = val[-1] if val.length else ''
489 if prefix is update_completions.prefix:
490 return
491 needle = prefix.toLowerCase().strip()
492
493 if needle:
494 interface_data = get_interface_data()
495 universe = update_completions.names if update_completions.prefix and needle.startswith(update_completions.prefix.toLowerCase()) else names
496 if interface_data.completion_mode is 'contains':
497 q = query_contains
498 else:
499 q = query_startswith
500 if library_data.categories_using_hierarchy and library_data.categories_using_hierarchy.indexOf(field) is not -1:
501 q = query_startswith_hierarchical
502 matching_names = [x for x in universe if q(x, needle) and x is not prefix]
503 else:
504 matching_names = []
505 update_completions.prefix = prefix
506 update_completions.names = matching_names
507 show_completions(container_id, div, field, prefix, matching_names)
508
509
510 update_completions.list_to_ui = None
511 update_completions.names = []
512 update_completions.prefix = ''
513
514
515 def line_edit_updated(container_id, field):
516 field_names_for(field, update_completions.bind(None, container_id))
517 update_removals(container_id)
518
519
520 def multiple_line_edit(list_to_ui, ui_to_list, container_id, book_id, field, fm, div, mi):
521 nonlocal value_to_json
522 update_completions.list_to_ui = list_to_ui
523 name = fm.name or field
524 le = E.input(
525 type='text', name=name.replace('#', '_c_'),
526 style='width: 100%', autocomplete='off', data_field=field,
527 oninput=line_edit_updated.bind(None, container_id, field)
528 )
529 val = (resolved_metadata(mi, field) or [])
530 if field is 'languages':
531 ln = mi.lang_names or {}
532 val = [ln[l] or l for l in val]
533 if list_to_ui:
534 val = val.join(list_to_ui)
535 le.value = val
536 form = create_form(le, line_edit_get_value, container_id, book_id, field)
537 if list_to_ui:
538 div.appendChild(E.div(style='margin: 0.5ex 1rem', _(
539 'Edit the "{0}" below. Multiple items can be separated by "{1}".').format(name, list_to_ui.strip())))
540 else:
541 div.appendChild(E.div(style='margin: 0.5ex 1rem', _(
542 'Edit the "{0}" below.').format(name)))
543 div.appendChild(E.div(style='margin: 0.5ex 1rem', form))
544 div.appendChild(E.div(style='margin: 0.5ex 1rem'))
545 div.appendChild(E.div(E.span(_('Loading all {}...').format(name)), style='margin: 0.5ex 1rem'))
546 le.focus(), le.select()
547 if list_to_ui:
548 value_to_json = def (raw):
549 seen = {}
550 ans = []
551 for x in [a.strip() for a in raw.split(ui_to_list) if a.strip()]:
552 if not seen[x]:
553 seen[x] = True
554 ans.push(x)
555 return ans
556 else:
557 value_to_json = identity
558 field_names_for(field, update_completions.bind(None, container_id))
559 update_removals(container_id)
560 # }}}
561
562 # Series edit {{{
563
564
565 def series_edit_get_value(container):
566 val = {
567 'series_name': container.querySelector('input[type="text"]').value,
568 'series_index': parseFloat(parseFloat(container.querySelector('input[type="number"]').value).toFixed(2)),
569 }
570 return True, val
571
572
573 def series_edit(container_id, book_id, field, fm, div, mi):
574 nonlocal value_to_json
575 name = fm.name or field
576 le = E.input(type='text', name=name.replace('#', '_c_'), style='width: 100%', oninput=line_edit_updated.bind(None, container_id, field), data_field=field)
577 le.value = resolved_metadata(mi, field) or ''
578 value_to_json = identity
579 ne = E.input(type='number', step='any', name=name.replace('#', '_c_') + '_index')
580 ne.value = parseFloat(parseFloat(resolved_metadata(mi, field + '_index')).toFixed(2))
581 table = E.table(style='width: 100%',
582 E.tr(E.td(_('Name:') + '\xa0'), E.td(le, style='width: 99%; padding-bottom: 1ex')),
583 E.tr(E.td(_('Number:') + '\xa0'), E.td(ne))
584 )
585 form = create_form(table, series_edit_get_value, container_id, book_id, field)
586 div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Edit the "{}" below.').format(name)))
587 div.appendChild(E.div(style='margin: 0.5ex 1rem', form))
588 div.appendChild(E.div(style='margin: 0.5ex 1rem'))
589 div.appendChild(E.div(E.span(_('Loading all {}...').format(name)), style='margin: 0.5ex 1rem'))
590 le.focus(), le.select()
591 field_names_for(field, update_completions.bind(None, container_id))
592 # }}}
593
594 # Date edit {{{
595
596
597 def date_edit_get_value(container):
598 return True, container.querySelector('input[type="date"]').value
599
600
601 def date_to_datetime(raw):
602 if not raw:
603 return UNDEFINED_DATE_ISO
604 return raw + 'T12:00:00+00:00' # we use 12 so that the date is the same in most timezones
605
606
607 def date_edit(container_id, book_id, field, fm, div, mi):
608 nonlocal value_to_json
609 value_to_json = date_to_datetime
610 name = fm.name or field
611 le = E.input(type='date', name=name.replace('#', '_c_'), min=UNDEFINED_DATE_ISO.split('T')[0], pattern='[0-9]{4}-[0-9]{2}-[0-9]{2}')
612 val = resolved_metadata(mi, field) or ''
613 if val:
614 val = format_date(val, 'yyyy-MM-dd')
615 le.value = val or ''
616 form = create_form(le, date_edit_get_value, container_id, book_id, field)
617
618 def clear(ev):
619 ev.currentTarget.closest('form').querySelector('input').value = ''
620
621 def today(ev):
622 ev.currentTarget.closest('form').querySelector('input').value = Date().toISOString().substr(0, 10)
623
624 form.firstChild.appendChild(
625 E.span(
626 '\xa0',
627 create_button(_('Clear'), action=clear),
628 '\xa0',
629 create_button(_('Today'), action=today),
630 ))
631 div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Edit the "{}" below.').format(name)))
632 div.appendChild(E.div(style='margin: 0.5ex 1rem', form))
633 le.focus(), le.select()
634
635 # }}}
636
637 # Identifiers edit {{{
638
639
640 def remove_identifier(evt):
641 li = evt.currentTarget.closest('li')
642 li.parentNode.removeChild(li)
643
644
645 def add_identifier(container_id, name, val):
646 c = document.getElementById(container_id)?.querySelector('.identifiers-edit')
647 if not c:
648 return
649 b = create_button(_('Remove'), action=remove_identifier)
650 c.appendChild(E.li(
651 style='padding-bottom: 1ex; margin-bottom: 1ex; border-bottom: solid 1px currentColor',
652 E.table(
653 style='width: 100%',
654 E.tr(
655 E.td(_('Type:') + '\xa0'),
656 E.td(style='padding-bottom: 1ex; width: 99%', E.input(type='text', style='width:100%', autocomplete=True, value=name or '')),
657 E.td(rowspan='2', style='padding: 0.5ex 1rem; vertical-align: middle', b),
658 ),
659 E.tr(E.td(_('Value:') + '\xa0'), E.td(E.input(type='text', style='width: 100%', autocomplete=True, value=val or ''))),
660 ),
661 ))
662
663
664 def identifiers_get_value(container):
665 ans = {}
666 for li in container.querySelectorAll('.identifiers-edit > li'):
667 n, v = li.querySelectorAll('input')
668 n, v = n.value, v.value
669 if n and v:
670 ans[n] = v
671 return True, ans
672
673
674 def identifiers_edit(container_id, book_id, field, fm, div, mi):
675 nonlocal value_to_json
676 name = fm.name or field
677 val = resolved_metadata(mi, 'identifiers') or {}
678 c = E.ul(class_='identifiers-edit', style='list-style-type: none')
679 form = create_form(c, identifiers_get_value, container_id, book_id, field)
680 bc = form.querySelector('.edit-form-button-container')
681 bc.insertBefore(create_button(_('Add identifier'), None, add_identifier.bind(None, container_id, '', '')), bc.firstChild)
682 bc.insertBefore(document.createTextNode('\xa0'), bc.lastChild)
683 div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Edit the "{}" below.').format(name)))
684 div.appendChild(E.div(style='margin: 0.5ex 1rem', form))
685 for k in Object.keys(val):
686 add_identifier(container_id, k, val[k])
687 value_to_json = identity
688 # }}}
689
690 # Rating edit {{{
691
692
693 def rating_get_value(container):
694 return True, parseInt(container.querySelector('.current-rating[data-rating]').getAttribute('data-rating'))
695
696
697 def set_rating(evt):
698 li = evt.currentTarget
699 for nli in li.closest('ul').childNodes:
700 nli.classList.remove('current-rating')
701 li.classList.add('current-rating')
702
703
704 def rating_edit(container_id, book_id, field, fm, div, mi):
705 nonlocal value_to_json
706 val = resolved_metadata(mi, field) or 0
707 numbers = list(range(11)) if fm.display?.allow_half_stars else list(range(0, 11, 2))
708 name = fm.name or field
709 c = E.ul(class_='rating-edit-container')
710 for n in numbers:
711 s = E.li(data_rating=n + '', onclick=set_rating)
712 c.appendChild(s)
713 if n is val:
714 s.classList.add('current-rating')
715 if n:
716 add_stars_to(s, n, numbers.length > 6)
717 else:
718 s.appendChild(document.createTextNode(_('Unrated')))
719 form = create_form(c, rating_get_value, container_id, book_id, field)
720 div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Choose the "{}" below').format(name)))
721 div.appendChild(E.div(style='margin: 0.5ex 1rem', form))
722 value_to_json = identity
723 # }}}
724
725 # Enum edit {{{
726
727
728 def enum_get_value(container):
729 return True, container.querySelector('.current-rating[data-rating]').getAttribute('data-rating')
730
731
732 def enum_edit(container_id, book_id, field, fm, div, mi):
733 nonlocal value_to_json
734 val = resolved_metadata(mi, field) or ''
735 name = fm.name or field
736 c = E.ul(class_='rating-edit-container')
737 for n in [''].concat(fm.display.enum_values):
738 s = E.li(data_rating=n + '', onclick=set_rating)
739 c.appendChild(s)
740 if n is val:
741 s.classList.add('current-rating')
742 s.appendChild(document.createTextNode(n or _('Blank')))
743 form = create_form(c, enum_get_value, container_id, book_id, field)
744 div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Choose the "{}" below').format(name)))
745 div.appendChild(E.div(style='margin: 0.5ex 1rem', form))
746 value_to_json = identity
747 # }}}
748
749 # Bool edit {{{
750
751
752 def bool_edit(container_id, book_id, field, fm, div, mi):
753 nonlocal value_to_json
754 val = resolved_metadata(mi, field)
755 if val:
756 val = 'y'
757 else:
758 if val is False:
759 val = 'n'
760 else:
761 val = ''
762 name = fm.name or field
763 c = E.ul(class_='rating-edit-container')
764 names = {'': _('Blank'), 'y': _('Yes'), 'n': _('No')}
765 for n in ['', 'y', 'n']:
766 s = E.li(data_rating=n + '', onclick=set_rating)
767 c.appendChild(s)
768 if n is val:
769 s.classList.add('current-rating')
770 s.appendChild(document.createTextNode(names[n]))
771 form = create_form(c, enum_get_value, container_id, book_id, field)
772 div.appendChild(E.div(style='margin: 0.5ex 1rem', _('Choose the "{}" below').format(name)))
773 div.appendChild(E.div(style='margin: 0.5ex 1rem', form))
774 val_map = {'': None, 'y': True, 'n': False}
775 value_to_json = def (x):
776 return val_map[x]
777 # }}}
778
779 # Cover edit {{{
780
781
782 def cover_chosen(top_container_id, book_id, container_id, files):
783 nonlocal has_changes, draft_changes
784 container = document.getElementById(container_id)
785 if not container:
786 return
787 if not files[0]:
788 return
789 file = files[0]
790 draft_changes.cover = file
791 has_changes = True
792 on_close(top_container_id)
793 cover_chosen.counter = 0
794
795
796 def remove_cover(top_container_id, book_id):
797 nonlocal has_changes, draft_changes
798 draft_changes.cover = '--remove--'
799 has_changes = True
800 on_close(top_container_id)
801
802
803 def cover_edit(container_id, book_id, field, fm, div, mi):
804 nonlocal has_changes, draft_changes
805 pending = {'file': None, 'remove': False}
806 object_url = None
807
808 panel = E.div(class_='cover-edit-layout')
809 panel.appendChild(E.h3(_('Edit cover')))
810 panel.appendChild(E.div(_('Changes apply only after pressing Save.'), class_='cover-edit-help'))
811
812 preview = E.div(class_='cover-edit-preview')
813 file_input = E.input(type='file', style='display:none', accept='.png, .jpeg, .jpg')
814 dropzone = E.div(
815 class_='cs-upload-dropzone',
816 preview,
817 E.span(_('Click anywhere on the cover to select a new cover or drag and drop a cover image.'), class_='cs-upload-dropzone-msg'),
818 file_input,
819 )
820 panel.appendChild(dropzone)
821
822 def refresh_preview():
823 nonlocal object_url
824 clear(preview)
825 if object_url:
826 try:
827 window.URL.revokeObjectURL(object_url)
828 except Exception:
829 pass
830 object_url = None
831 if pending.remove:
832 preview.appendChild(E.div(
833 _('Cover will be removed'),
834 style='height:100%;display:flex;align-items:center;justify-content:center;opacity:0.75;font-weight:700;'
835 ))
836 return
837 img = E.img()
838 if pending.file:
839 object_url = window.URL.createObjectURL(pending.file)
840 img.src = object_url
841 else:
842 img.src = cover_url(book_id)
843 preview.appendChild(img)
844
845 def handle_files(files):
846 f = files and files[0]
847 if not f:
848 return
849 pending.file = f
850 pending.remove = False
851 refresh_preview()
852
853 file_input.addEventListener('change', def (): handle_files(file_input.files);, False)
854 dropzone.addEventListener('click', def (ev): file_input.click();, False)
855
856 def stop(e):
857 e.stopPropagation()
858 e.preventDefault()
859
860 def drop(e):
861 stop(e)
862 handle_files(e.dataTransfer.files)
863
864 dropzone.addEventListener('dragenter', stop, False)
865 dropzone.addEventListener('dragover', stop, False)
866 dropzone.addEventListener('drop', drop, False)
867
868 actions = E.div(class_='cover-edit-actions')
869 actions.appendChild(create_button(_('Remove existing cover'), action=def (ev):
870 pending.file = None
871 pending.remove = True
872 refresh_preview()
873 ))
874 panel.appendChild(actions)
875
876 footer = E.div(class_='edit-form-button-container')
877
878 def do_save(ev):
879 nonlocal has_changes
880
881 def revoke():
882 if object_url:
883 try:
884 window.URL.revokeObjectURL(object_url)
885 except Exception:
886 pass
887
888 def on_file_read(evt):
889 nonlocal has_changes
890 draft_changes.cover = evt.target.result
891 has_changes = True
892 on_close(container_id)
893
894 if pending.remove:
895 draft_changes.cover = '--remove--'
896 has_changes = True
897 revoke()
898 on_close(container_id)
899 elif pending.file:
900 r = FileReader()
901 r.onload = on_file_read
902 revoke()
903 r.readAsDataURL(pending.file)
904 else:
905 revoke()
906 on_close(container_id)
907
908 footer.appendChild(create_button(_('Save'), icon='check', action=do_save, highlight=True))
909 footer.appendChild(E.span('\xa0'))
910 footer.appendChild(create_button(_('Cancel'), icon='close', action=def (ev):
911 if object_url:
912 try:
913 window.URL.revokeObjectURL(object_url)
914 except Exception:
915 pass
916 on_close(container_id)
917 ))
918 panel.appendChild(footer)
919 div.appendChild(panel)
920 refresh_preview()
921
922 # }}}
923
924 # Formats edit {{{
925
926
927 def format_added(top_container_id, book_id, container_id, files):
928 nonlocal has_changes, draft_changes
929 container = document.getElementById(container_id)
930 if not container:
931 return
932 if not files[0]:
933 return
934 added = draft_changes.added_formats or []
935 for file in files:
936 ext = file.name.rpartition('.')[-1]
937 data = {'name': file.name, 'size': file.size, 'type': file.type, 'data_url': None, 'ext': ext}
938 added.push(data)
939 r = FileReader()
940 r.onload = def (evt):
941 data.data_url = evt.target.result
942 r.readAsDataURL(file)
943 draft_changes.added_formats = added
944 has_changes = True
945 on_close(top_container_id)
946
947
948 def remove_format(top_container_id, book_id, fmt):
949 nonlocal has_changes, draft_changes
950 has_changes = True
951 removed_formats = draft_changes.removed_formats or []
952 removed_formats.push(fmt.toUpperCase())
953 draft_changes.removed_formats = removed_formats
954 on_close(top_container_id)
955
956
957 def formats_edit(container_id, book_id, field, fm, div, mi):
958 upload_files_widget(div, format_added.bind(None, container_id, book_id), _(
959 'Add a format by <a>selecting the book file</a> or drag and drop of the book file here.'),
960 single_file=True)
961 remove_buttons = E.div(style='padding: 1rem; display: flex; flex-wrap: wrap; align-content: flex-start')
962 formats = resolved_formats(mi.formats)
963 for i, fmt in enumerate(formats):
964 remove_buttons.appendChild(create_button(
965 _('Remove {}').format(fmt.upper()), action=remove_format.bind(None, container_id, book_id, fmt.upper())))
966 remove_buttons.lastChild.style.marginBottom = '1ex'
967 remove_buttons.lastChild.style.marginRight = '1rem'
968
969 div.appendChild(remove_buttons)
970
971 # }}}
972
973
974 def switch_to_edit_panel(container):
975 d = container.querySelector('div[data-ctype="edit"]')
976 d.style.display = 'block'
977 container.dataset.modal = '1'
978 # Dim the underlying panel (visual modal effect).
979 d.previousSibling.style.opacity = '0.5'
980 d.previousSibling.style.pointerEvents = 'none'
981 d.previousSibling.style.filter = 'blur(1px)'
982 # Make the edit panel a floating modal window.
983 d.style.position = 'fixed'
984 d.style.left = '50%'
985 d.style.top = '10vh'
986 d.style.transform = 'translateX(-50%)'
987 d.style.width = 'min(980px, calc(100% - 2rem))'
988 d.style.maxHeight = '80vh'
989 d.style.overflow = 'auto'
990 d.style.zIndex = '1001'
991 d.style.backgroundColor = 'var(--calibre-color-window-background)'
992 d.style.border = 'var(--calibre-border-style-subtle)'
993 d.style.borderRadius = '16px'
994 d.style.boxShadow = '0 24px 64px rgba(0,0,0,0.18)'
995 d.style.padding = '1rem'
996 clear(d)
997 return d
998
999
1000 def edit_field(container_id, book_id, field):
1001 nonlocal value_to_json
1002 fm = library_data.field_metadata[field]
1003 c = document.getElementById(container_id)
1004 mi = book_metadata(book_id)
1005 if not c or not fm or not mi:
1006 return
1007 d = switch_to_edit_panel(c)
1008 update_completions.ui_to_list = None
1009 update_completions.list_to_ui = None
1010 update_completions.names = []
1011 update_completions.prefix = ''
1012 if field is 'authors':
1013 multiple_line_edit(' & ', '&', container_id, book_id, field, fm, d, mi)
1014 elif field is 'cover':
1015 cover_edit(container_id, book_id, field, fm, d, mi)
1016 elif field is 'formats':
1017 formats_edit(container_id, book_id, field, fm, d, mi)
1018 elif fm.datatype is 'series':
1019 series_edit(container_id, book_id, field, fm, d, mi)
1020 elif fm.datatype is 'datetime':
1021 date_edit(container_id, book_id, field, fm, d, mi)
1022 elif fm.datatype is 'rating':
1023 rating_edit(container_id, book_id, field, fm, d, mi)
1024 elif fm.datatype is 'enumeration':
1025 enum_edit(container_id, book_id, field, fm, d, mi)
1026 elif fm.datatype is 'bool':
1027 bool_edit(container_id, book_id, field, fm, d, mi)
1028 elif fm.datatype is 'int' or fm.datatype is 'float':
1029 number_edit(container_id, book_id, field, fm, d, mi)
1030 elif field is 'identifiers':
1031 identifiers_edit(container_id, book_id, field, fm, d, mi)
1032 elif fm.datatype is 'comments' or field is 'comments':
1033 ias = fm.display?.interpret_as
1034 if ias is 'short-text':
1035 simple_line_edit(container_id, book_id, field, fm, d, mi)
1036 elif ias is 'long-text':
1037 text_edit(container_id, book_id, field, fm, d, mi)
1038 elif ias is 'markdown':
1039 text_edit(container_id, book_id, field, fm, d, mi, field + '#markdown#')
1040 else:
1041 html_edit(container_id, book_id, field, fm, d, mi)
1042 else:
1043 if fm.link_column:
1044 multiple_line_edit(fm.is_multiple?.list_to_ui, fm.is_multiple?.ui_to_list, container_id, book_id, field, fm, d, mi)
1045 else:
1046 simple_line_edit(container_id, book_id, field, fm, d, mi)
1047 if field is 'title':
1048 value_to_json = def (x):
1049 return x or _('Untitled')
1050 elif field is 'authors':
1051 value_to_json = def (x):
1052 ans = [a.strip() for a in x.split('&') if a.strip()]
1053 if not ans.length:
1054 ans = [_('Unknown')]
1055 return ans
1056
1057
1058 def render_metadata(mi, table, container_id, book_id): # {{{
1059 field_metadata = library_data.field_metadata
1060 interface_data = get_interface_data()
1061 current_edit_action = None
1062
1063 def allowed_fields(field):
1064 fm = field_metadata[field]
1065 if not fm:
1066 return False
1067 if field.endswith('_index'):
1068 pfm = field_metadata[field[:-len('_index')]]
1069 if pfm and pfm.datatype is 'series':
1070 return False
1071 if fm.datatype is 'composite':
1072 return False
1073 if field.startswith('#'):
1074 return True
1075 if field in IGNORED_FIELDS or field.endswith('_sort') or field[0] is '@':
1076 return False
1077 return True
1078
1079 fields = library_data.book_display_fields
1080 if not fields or not fields.length:
1081 fields = sorted(filter(allowed_fields, mi), key=field_sorter(field_metadata))
1082 else:
1083 fields = filter(allowed_fields, fields)
1084 fields = list(fields)
1085 added_fields = {f: True for f in fields}
1086 if not added_fields.title:
1087 added_fields.title = True
1088 fields.insert(0, 'title')
1089 for other_field in Object.keys(library_data.field_metadata):
1090 if not added_fields[other_field] and allowed_fields(other_field) and other_field not in IGNORED_FIELDS:
1091 fields.push(other_field)
1092
1093 def add_row(name, val, is_html=False, join=None):
1094 if val is undefined or val is None:
1095 val = [' '] if join else '\xa0'
1096
1097 def add_val(v):
1098 if not v.appendChild:
1099 v += ''
1100 if v.appendChild:
1101 table.lastChild.lastChild.appendChild(v)
1102 else:
1103 table.lastChild.lastChild.appendChild(document.createTextNode(v))
1104
1105 table.appendChild(E.tr(onclick=current_edit_action, E.td(name), E.td()))
1106 if is_html:
1107 table.lastChild.lastChild.appendChild(document.createTextNode(truncated_html(val + '')))
1108 else:
1109 if not join:
1110 add_val(val)
1111 else:
1112 for v in val:
1113 add_val(v)
1114 if v is not val[-1]:
1115 table.lastChild.lastChild.appendChild(document.createTextNode(join))
1116 return table.lastChild.lastChild
1117
1118 def process_composite(field, fm, name, val):
1119 if fm.display and fm.display.contains_html:
1120 add_row(name, val, is_html=True)
1121 elif fm.is_multiple and fm.is_multiple.list_to_ui:
1122 all_vals = filter(None, map(str.strip, val.split(fm.is_multiple.list_to_ui)))
1123 add_row(name, all_vals, join=fm.is_multiple.list_to_ui)
1124 else:
1125 add_row(name, val)
1126
1127 def process_authors(field, fm, name, val):
1128 add_row(name, val, join=' & ')
1129
1130 def process_publisher(field, fm, name, val):
1131 add_row(name, val)
1132
1133 def process_rating(field, fm, name, val):
1134 stars = E.span()
1135 val = int(val or 0)
1136 if val > 0:
1137 for i in range(val // 2):
1138 stars.appendChild(svgicon('star'))
1139 if fm.display.allow_half_stars and (val % 2):
1140 stars.appendChild(svgicon('star-half'))
1141 add_row(name, stars)
1142 else:
1143 add_row(name, None)
1144
1145 def process_identifiers(field, fm, name, val):
1146 if val:
1147 keys = Object.keys(val)
1148 if keys.length:
1149 table.appendChild(E.tr(onclick=current_edit_action, E.td(name), E.td()))
1150 td = table.lastChild.lastChild
1151 for k in keys:
1152 if td.childNodes.length:
1153 td.appendChild(document.createTextNode(', '))
1154 td.appendChild(document.createTextNode(k))
1155 return
1156 add_row(name, None)
1157
1158 def process_languages(field, fm, name, val):
1159 if val and val.length:
1160 table.appendChild(E.tr(onclick=current_edit_action, E.td(name), E.td()))
1161 td = table.lastChild.lastChild
1162 for k in val:
1163 lang = k
1164 if mi.lang_names and mi.lang_names[k]:
1165 lang = mi.lang_names[k]
1166 td.appendChild(document.createTextNode(lang))
1167 if k is not val[-1]:
1168 td.appendChild(document.createTextNode(', '))
1169 return
1170 add_row(name, None)
1171
1172 def process_datetime(field, fm, name, val):
1173 if val:
1174 fmt = interface_data['gui_' + field + '_display_format'] or (fm['display'] or {}).date_format
1175 add_row(name, format_date(val, fmt))
1176 else:
1177 add_row(name, None)
1178
1179 def process_series(field, fm, name, val):
1180 if val:
1181 ifield = field + '_index'
1182 try:
1183 ival = float(resolved_metadata(mi, ifield))
1184 except Exception:
1185 ival = 1.0
1186 ival = fmt_sidx(ival, use_roman=interface_data.use_roman_numerals_for_series_number)
1187 table.appendChild(E.tr(onclick=current_edit_action, E.td(name), E.td()))
1188 s = safe_set_inner_html(E.span(), _('{0} of <i>{1}</i>').format(ival, val))
1189 table.lastChild.lastChild.appendChild(s)
1190 else:
1191 add_row(name, None)
1192
1193 def process_formats(field, fm, name, val):
1194 val = resolved_formats(val)
1195 if val.length:
1196 join = fm.is_multiple.list_to_ui if fm.is_multiple else None
1197 add_row(name, val, join=join)
1198 else:
1199 add_row(name, None)
1200
1201 def process_field(field, fm):
1202 name = fm.name or field
1203 datatype = fm.datatype
1204 val = resolved_metadata(mi, field)
1205 if field is 'comments' or datatype is 'comments':
1206 add_row(name, truncated_html(val or ''))
1207 return
1208 func = None
1209 if datatype is 'composite':
1210 func = process_composite
1211 elif datatype is 'rating':
1212 func = process_rating
1213 elif field is 'identifiers':
1214 func = process_identifiers
1215 elif field is 'authors':
1216 func = process_authors
1217 elif field is 'publisher':
1218 func = process_publisher
1219 elif field is 'languages':
1220 func = process_languages
1221 elif field is 'formats':
1222 func = process_formats
1223 elif datatype is 'datetime':
1224 func = process_datetime
1225 elif datatype is 'series':
1226 func = process_series
1227 if func:
1228 func(field, fm, name, val)
1229 else:
1230 if datatype is 'text' or datatype is 'enumeration':
1231 if val is not undefined and val is not None:
1232 join = fm.is_multiple.list_to_ui if fm.is_multiple else None
1233 add_row(name, val, join=join)
1234 else:
1235 add_row(name, None)
1236 elif datatype is 'bool':
1237 add_row(name, _('Yes') if val else (_('No') if val? else ''))
1238 elif datatype is 'int' or datatype is 'float':
1239 if val is not undefined and val is not None:
1240 fmt = (fm.display or {}).number_format
1241 if fmt:
1242 val = fmt.format(val)
1243 else:
1244 val += ''
1245 add_row(name, val)
1246 else:
1247 add_row(name, None)
1248
1249 for field in fields:
1250 fm = field_metadata[field]
1251 if not fm:
1252 continue
1253 current_edit_action = edit_field.bind(None, container_id, book_id, field)
1254 try:
1255 process_field(field, fm)
1256 except Exception:
1257 print('Failed to render metadata field: ' + field)
1258 traceback.print_exc()
1259
1260 current_edit_action = edit_field.bind(None, container_id, book_id, 'cover')
1261 table.appendChild(E.tr(onclick=current_edit_action, E.td(_('Cover')), E.td()))
1262 img = E.img(
1263 style='max-width: 100%; max-height: 400px',
1264 )
1265 if draft_changes.cover:
1266 if draft_changes.cover is '--remove--':
1267 img.removeAttribute('src')
1268 else:
1269 img.src = draft_changes.cover
1270 else:
1271 img.src = cover_url(book_id)
1272 table.lastChild.lastChild.appendChild(img)
1273 # }}}
1274
1275
1276 def changes_submitted(container_id, book_id, end_type, xhr, ev):
1277 nonlocal changes, has_changes
1278 changes = {}
1279 has_changes = False
1280 if end_type is 'abort':
1281 on_close(container_id)
1282 return
1283 if end_type is not 'load':
1284 error_dialog(_('Failed to update metadata on server'), _(
1285 'Updating metadata for the book: {} failed.').format(book_id), xhr.error_html)
1286 return
1287 try:
1288 dirtied = JSON.parse(xhr.responseText)
1289 except Exception as err:
1290 error_dialog(_('Could not update metadata for book'), _('Server returned an invalid response'), err.toString())
1291 return
1292
1293 cq = get_current_query()
1294 if cq.from_read_book:
1295 window.parent.postMessage(
1296 {
1297 'type': 'update_cached_book_metadata', 'library_id': cq.library_id,
1298 'book_id': cq.book_id, 'metadata': dirtied[book_id], 'from_read_book': cq.from_read_book,
1299 },
1300 document.location.protocol + '//' + document.location.host
1301 )
1302 else:
1303 for bid in dirtied:
1304 set_book_metadata(bid, dirtied[bid])
1305 on_close(container_id)
1306
1307
1308 def on_progress(container_id, book_id, loaded, total, xhr):
1309 container = document.getElementById(container_id)
1310 if container and total:
1311 update_status_widget(container, loaded, total)
1312
1313
1314 def edit_note(field, item):
1315 show_note(field, 0, item, panel='edit_note')
1316
1317
1318 def show_select_panel():
1319 q = parse_url_params()
1320 q.panel = 'select_item_for_edit_notes'
1321 push_state(q, replace=False)
1322
1323
1324 def select_item_for_edit_notes(container, mi):
1325 set_title(container, _('Edit notes'))
1326 field_metadata = library_data.field_metadata
1327
1328 def allowed_fields(field):
1329 fm = field_metadata[field]
1330 if not fm:
1331 return False
1332 return library_data.fields_that_support_notes.indexOf(field) > -1
1333
1334 container.appendChild(E.div(style='padding: 0.5rem'))
1335 d = container.lastChild
1336 d.appendChild(E.div(svgicon('pencil'), ' ', _('Tap on an item below to edit the notes associated with it.'), style='margin-bottom: 0.5rem'))
1337 dl = E.dl()
1338 fields = sorted(filter(allowed_fields, mi), key=field_sorter(field_metadata))
1339 for field in fields:
1340 val = resolved_metadata(mi, field)
1341 fm = field_metadata[field]
1342 if val:
1343 dl.appendChild(E.dt(fm.name))
1344 if jstype(val) is 'string':
1345 val = [val]
1346 dd = E.dd(style='text-indent: 1em; margin-bottom: 0.5em')
1347 dl.appendChild(dd)
1348 for i, x in enumerate(val):
1349 a = E.a(x, href='javascript:void(0)', class_='blue-link', onclick=edit_note.bind(None, field, x))
1350 dd.appendChild(a)
1351 if i < val.length - 1:
1352 dd.appendChild(document.createTextNode(fm.is_multiple.list_to_ui))
1353
1354 if dl.firstChild:
1355 d.appendChild(dl)
1356 else:
1357 d.appendChild(E.div(_('This book has no authors/series/etc. that can have notes added to them')))
1358
1359
1360 def submit_changes(container_id, book_id):
1361 c = document.getElementById(container_id)
1362 d = c.querySelector('div[data-ctype="show"]')
1363 clear(d)
1364 d.appendChild(E.div(style='margin: 1ex 1rem', _('Uploading changes to server, please wait...')))
1365 data = {'changes': changes, 'loaded_book_ids': loaded_book_ids()}
1366 w = upload_status_widget()
1367 d.appendChild(w)
1368 ajax_send(
1369 f'cdb/set-fields/{book_id}/{current_library_id()}',
1370 data,
1371 changes_submitted.bind(None, container_id, book_id),
1372 on_progress.bind(None, container_id, book_id)
1373 )
1374
1375
1376 def show_book(container_id, book_id):
1377 container = document.getElementById(container_id)
1378 mi = book_metadata(book_id)
1379 if not container or not mi:
1380 return
1381 div = container.querySelector('div[data-ctype="show"]')
1382 if not div:
1383 return
1384 clear(div)
1385 cq = get_current_query()
1386 if has_changes:
1387 div.appendChild(E.div(
1388 style='margin: 1ex 1rem',
1389 E.div(_('You have unsaved changes.')),
1390 E.div(_('Use Save/Cancel below to apply or discard them.')),
1391 ))
1392 else:
1393 div.appendChild(E.div(
1394 style='margin: 1ex 1rem',
1395 E.div(_('Tap any field below to edit that field.')),
1396 E.div(
1397 E.a(svgicon('pencil'), '\xa0', _('Add notes for authors, series, etc.'),
1398 href='javascript:void(0)', onclick=show_select_panel, class_='blue-link'),
1399 style='display:' + ('none' if cq.from_read_book else 'block'),
1400 ),
1401 ))
1402 div.appendChild(E.table(class_='metadata'))
1403 render_metadata(mi, div.lastChild, container_id, book_id)
1404
1405 def save_action(ev=None):
1406 nonlocal changes, draft_changes, has_changes
1407 changes = draft_changes
1408 draft_changes = {}
1409 has_changes = False
1410 submit_changes(container_id, book_id)
1411
1412 def cancel_action(ev=None):
1413 nonlocal draft_changes, has_changes
1414 draft_changes = {}
1415 has_changes = False
1416 show_book(container_id, book_id)
1417
1418 if has_changes:
1419 div.appendChild(E.div(
1420 class_='edit-metadata-footer',
1421 style='display:flex;justify-content:center;align-items:center;gap:0.75rem;flex-wrap:wrap;padding:0 1rem 1.5rem 1rem',
1422 create_button(_('Save'), None, save_action, highlight=True),
1423 create_button(_('Cancel'), None, cancel_action),
1424 ))
1425
1426
1427 def is_edit_panel_showing(container):
1428 d = container.querySelector('div[data-ctype="edit"]')
1429 return bool(d and d.style.display is 'block')
1430
1431
1432 def close_edit_panel(container):
1433 d = container.querySelector('div[data-ctype="edit"]')
1434 d.style.display = 'none'
1435 container.dataset.modal = ''
1436 d.previousSibling.style.opacity = ''
1437 d.previousSibling.style.pointerEvents = ''
1438 d.previousSibling.style.filter = ''
1439 clear(d)
1440
1441
1442 def on_close(container_id):
1443 cq = get_current_query()
1444 if cq.panel is 'select_item_for_edit_notes':
1445 back()
1446 return
1447 c = document.getElementById(container_id)
1448 if c:
1449 if is_edit_panel_showing(c):
1450 close_edit_panel(c)
1451 q = parse_url_params()
1452 show_book(container_id, int(q.book_id))
1453 c.querySelector(f'.{CLASS_NAME}').focus()
1454 return
1455 if cq.from_read_book:
1456 window.parent.postMessage(
1457 {'type': 'edit_metadata_closed', 'from_read_book': cq.from_read_book},
1458 document.location.protocol + '//' + document.location.host
1459 )
1460 else:
1461 if has_changes:
1462 question_dialog(_('Are you sure?'), _(
1463 'Any changes you have made will be discarded.'
1464 ' Do you wish to discard all changes?'), def (yes):
1465 if yes:
1466 back()
1467 )
1468 else:
1469 back()
1470
1471
1472 def proceed_after_succesful_fetch_metadata(container_id, book_id):
1473 nonlocal changes, draft_changes, has_changes
1474 changes = {}
1475 draft_changes = {}
1476 has_changes = False
1477 container = document.getElementById(container_id)
1478 mi = book_metadata(book_id)
1479 if not mi or not container:
1480 if get_current_query().from_read_book:
1481 container.textContent = _('Failed to read metadata for book')
1482 return
1483 show_panel('book_details', query=parse_url_params(), replace=True)
1484 return
1485 cq = get_current_query()
1486 clear(container.lastChild)
1487 if cq.panel is 'select_item_for_edit_notes':
1488 select_item_for_edit_notes(container, mi)
1489 return
1490 set_title(container, _('Edit metadata for {}').format(mi.title))
1491 container.lastChild.appendChild(E.div(data_ctype='show', style='display:block'))
1492 container.lastChild.appendChild(E.div(data_ctype='edit', style='display:none'))
1493 show_book(container_id, book_id)
1494
1495
1496 def create_edit_metadata(container):
1497 q = parse_url_params()
1498 current_book_id = q.book_id
1499 if not current_book_id:
1500 no_book(container)
1501 return
1502 current_book_id = int(current_book_id)
1503 container_id = container.parentNode.id
1504 if not book_metadata(current_book_id):
1505 fetch_metadata(container_id, current_book_id, proceed_after_succesful_fetch_metadata)
1506 else:
1507 proceed_after_succesful_fetch_metadata(container_id, current_book_id)
1508
1509
1510 def check_for_books_loaded():
1511 container = this
1512 if load_status.loading:
1513 conditional_timeout(container.id, 5, check_for_books_loaded)
1514 return
1515 container = container.lastChild
1516 clear(container)
1517 if not load_status.ok:
1518 report_load_failure(container)
1519 return
1520 create_edit_metadata(container)
1521
1522
1523 def handle_keypress(container_id, ev):
1524 if not ev.altKey and not ev.ctrlKey and not ev.metaKey and not ev.shiftKey:
1525 if ev.key is 'Escape':
1526 ev.preventDefault(), ev.stopPropagation()
1527 on_close(container_id)
1528
1529
1530 def init(container_id):
1531 container = document.getElementById(container_id)
1532 create_top_bar(container, title=_('Edit metadata'), action=on_close.bind(None, container_id), icon='close')
1533 container.appendChild(E.div(class_=CLASS_NAME, tabindex='0', onkeydown=handle_keypress.bind(None, container_id)))
1534 container.lastChild.focus()
1535 container.lastChild.appendChild(E.div(_('Loading books from the calibre library, please wait...'), style='margin: 1ex 1em'))
1536 conditional_timeout(container_id, 5, check_for_books_loaded)
1537
1538
1539 def init_select_item_for_edit_notes(container_id):
1540 q = parse_url_params()
1541 book_whose_metadata_is_being_edited(int(q.book_id))
1542 container = document.getElementById(container_id)
1543 create_top_bar(container, title=_('Edit metadata'), action=on_close.bind(None, container_id), icon='close')
1544 container.appendChild(E.div(class_=CLASS_NAME, tabindex='0', onkeydown=handle_keypress.bind(None, container_id)))
1545 container.lastChild.focus()
1546 container.lastChild.appendChild(E.div(_('Loading books from the calibre library, please wait...'), style='margin: 1ex 1em'))
1547 conditional_timeout(container_id, 5, check_for_books_loaded)
1548
1549
1550 def set_panel_handlers():
1551 set_panel_handler('edit_metadata', init)
1552 set_panel_handler('select_item_for_edit_notes', init_select_item_for_edit_notes)