Debian Codegraph @

src/pyj/book_list/views.pyj

raw
1 # vim:fileencoding=utf-8
2 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
3 from __python__ import hash_literals
4
5 import traceback
6 from elementmaker import E
7 from gettext import gettext as _, ngettext
8
9 from ajax import ajax_send
10 from book_list.add import add_books_panel
11 from book_list.cover_grid import (
12 append_item as cover_grid_append_item, cover_grid_css,
13 create_item as create_cover_grid_item, description as COVER_GRID_DESCRIPTION,
14 init as init_cover_grid, create_cover_grid_size_control, sync_cover_grid_size_control
15 )
16 from book_list.custom_list import (
17 append_item as custom_list_append_item, create_item as create_custom_list_item,
18 custom_list_css, description as CUSTOM_LIST_DESCRIPTION,
19 init as init_custom_list
20 )
21 from book_list.details_list import (
22 append_item as details_list_append_item, create_item as create_details_list_item,
23 description as DETAILS_LIST_DESCRIPTION, details_list_css,
24 init as init_details_list
25 )
26 from book_list.globals import get_session_data
27 from book_list.item_list import create_item, create_item_list
28 from book_list.library_data import (
29 add_more_books, all_virtual_libraries, book_metadata, current_book_ids,
30 current_library_id, current_sorted_field, ensure_current_library_data, library_data, load_status,
31 loaded_books_query, refresh_sidebar_navigation, thumbnail_cache, url_books_query
32 )
33 from book_list.router import back, home, push_state, update_window_title
34 from book_list.saved_virtual_libraries import save_saved_virtual_library
35 from book_list.saved_virtual_library_dialog import show_saved_virtual_library_dialog
36 from book_list.search import (
37 init as init_search_panel, set_apply_search, tb_config_panel_handler
38 )
39 from book_list.top_bar import add_button, create_top_bar, set_title_tooltip
40 from book_list.ui import query_as_href, set_panel_handler, show_panel
41 from dom import add_extra_css, build_rule, clear, ensure_id, set_css, svgicon
42 from modals import error_dialog
43 from session import get_interface_data
44 from utils import conditional_timeout, parse_url_params, safe_set_inner_html
45 from widgets import create_button, create_pager_widget, create_spinner, enable_escape_key, create_select
46
47 CLASS_NAME = 'book-list-container'
48 ITEM_CLASS_NAME = 'book-list-item'
49 ALLOWED_MODES = {'cover_grid', 'details_list', 'custom_list'}
50 DEFAULT_MODE = 'cover_grid'
51
52 add_extra_css(def ():
53 sel = '.' + CLASS_NAME + ' '
54 # Unified page gutter for all first-level children
55 ans = sel + r'''{
56 padding-left: 1rem; padding-right: 1rem;
57 @media (max-width: 720px) {
58 padding-left: 0.75rem; padding-right: 0.75rem;
59 }
60 }
61 .calibre-showing-label {
62 & > span:last-of-type { display: none; }
63 @media (max-width: 420px) {
64 & > span:last-of-type { display: inline; }
65 & > span:first-of-type { display: none; }
66 }
67 }
68 [data-component="book_list"] a { color: currentColor; }
69 [data-component="book_list"] a:visited { color: currentColor; }
70 '''
71 ans += build_rule(sel + '.' + ITEM_CLASS_NAME,
72 min_width='0',
73 max_width='100%',
74 box_sizing='border-box',
75 )
76 ans += cover_grid_css()
77 ans += details_list_css()
78 ans += custom_list_css()
79 return ans
80 )
81
82 book_list_data = {
83 'container_id': None, 'shown_book_ids': set(), 'mode': None, 'fetching_more_books': None,
84 }
85
86
87 def parse_int(x, default_value):
88 try:
89 x = int(x)
90 except Exception:
91 x = default_value
92 return x
93
94
95 def clamp(n, lo, hi):
96 return max(lo, min(hi, n))
97
98
99 def component(name):
100 return document.getElementById(book_list_data.container_id).querySelector(f'[data-component="{name}"]')
101
102
103 def clear_grid():
104 # We replace the div entirely so that any styles associated with it are also removed.
105 e = component('book_list')
106 if not e:
107 return
108 parent = e.parentNode
109 if not parent:
110 return
111 bl = E.div(data_component='book_list')
112 parent.insertBefore(bl, e)
113 parent.removeChild(e)
114 book_list_data.init_grid(bl)
115
116
117 def has_parent_with_class(elem, cls):
118 while elem:
119 if elem.classList and elem.classList.contains(cls):
120 return elem
121 elem = elem.parentNode
122
123
124 def save_scroll_position():
125 container = document.getElementById(book_list_data.container_id)
126 if container:
127 left, top = container.offsetLeft, container.offsetTop
128 for y in range(5, 100, 5):
129 for x in range(25, 125, 5):
130 elem = document.elementFromPoint(left + x, top + y)
131 p = has_parent_with_class(elem, ITEM_CLASS_NAME)
132 if p:
133 q = parse_url_params()
134 q.book_id = p.dataset.bookId
135 push_state(q, replace=True, call_handler=False)
136 return
137
138
139 def show_subsequent_panel(name, query=None, replace=False):
140 save_scroll_position()
141 show_panel(name, query, replace)
142
143
144 def show_add_books():
145 show_subsequent_panel('book_list^add')
146
147
148 def show_random_book():
149 show_subsequent_panel('book_details', {'book_id': '0'})
150
151
152 def add_book_list_top_bar_buttons(container):
153 add_button(container, 'plus', show_add_books, _('Add books to the library'))
154 add_button(container, 'random', show_random_book, _('Choose a random book from the library'))
155
156
157 def on_book_click(book_id, evt):
158 evt.preventDefault()
159 show_subsequent_panel('book_details', {'book_id': book_id})
160
161
162 def create_image(book_id, max_width, max_height, on_load):
163 return thumbnail_cache.get(book_id, max_width, max_height, on_load)
164
165
166 def render_id(book_id):
167 l = book_list_data.shown_book_ids.length
168 book_list_data.shown_book_ids.add(book_id)
169 if l < book_list_data.shown_book_ids.length:
170 metadata = book_metadata(book_id)
171 ans = book_list_data.render_book(
172 book_id,
173 metadata,
174 create_image,
175 on_book_click.bind(None, book_id),
176 query_as_href({'book_id': book_id + ''}, 'book_details')
177 )
178 ans.classList.add(ITEM_CLASS_NAME)
179 ans.dataset.bookId = str(book_id)
180 return ans
181
182
183 def render_ids(book_ids):
184 book_ids = book_ids or current_book_ids()
185 div = component('book_list')
186 if div:
187 for book_id in book_ids:
188 child = render_id(book_id)
189 if child:
190 book_list_data.append_item(div, child)
191
192
193 def get_view_mode():
194 idata = get_interface_data()
195 mode = get_session_data().get('view_mode', idata.default_book_list_mode)
196 if mode not in ('cover_grid', 'details_list', 'custom_list'):
197 mode = DEFAULT_MODE
198 return mode
199
200
201 def setup_view_mode(mode, book_list_data):
202 if mode not in ALLOWED_MODES:
203 mode = DEFAULT_MODE
204 book_list_data.mode = mode
205 if mode is 'cover_grid':
206 book_list_data.render_book = create_cover_grid_item
207 book_list_data.init_grid = init_cover_grid
208 book_list_data.append_item = cover_grid_append_item
209 elif mode is 'details_list':
210 book_list_data.render_book = create_details_list_item
211 book_list_data.init_grid = init_details_list
212 book_list_data.append_item = details_list_append_item
213 elif mode is 'custom_list':
214 book_list_data.render_book = create_custom_list_item
215 book_list_data.init_grid = init_custom_list
216 book_list_data.append_item = custom_list_append_item
217 return mode
218
219
220 def apply_view_mode(mode=DEFAULT_MODE):
221 if book_list_data.mode is not mode:
222 setup_view_mode(mode, book_list_data)
223 # We are switching the renderer, so the current DOM needs a full re-render.
224 # Reset shown ids so render_ids() actually repopulates the new grid/list.
225 book_list_data.shown_book_ids = set()
226 clear_grid()
227 render_ids()
228 return mode
229
230
231 # More button {{{
232
233
234 def update_fetching_status():
235 more = component('more_button')
236 if not more:
237 return
238 if book_list_data.fetching_more_books:
239 more.firstChild.style.display = 'none'
240 more.lastChild.style.display = 'block'
241 elif library_data.search_result.total_num > book_list_data.shown_book_ids.length:
242 more.firstChild.style.display = 'block'
243 more.lastChild.style.display = 'none'
244 else:
245 more.firstChild.style.display = 'none'
246 more.lastChild.style.display = 'none'
247
248
249 def abort_get_more_books(no_update):
250 if book_list_data.fetching_more_books:
251 book_list_data.fetching_more_books.abort()
252 book_list_data.fetching_more_books = None
253 if not no_update:
254 update_fetching_status()
255
256
257 def got_more_books(end_type, xhr, event):
258 if book_list_data.fetching_more_books is not xhr:
259 return # Fetching was aborted
260 book_list_data.fetching_more_books = None
261 update_fetching_status()
262 if end_type is 'load':
263 try:
264 data = JSON.parse(xhr.responseText)
265 if not data.search_result.book_ids:
266 raise Exception('No books ids object in search result from server')
267 add_more_books(data)
268 render_ids(data.search_result.book_ids)
269 except Exception:
270 error_dialog(_('Could not get more books'), _('Server returned an invalid response'), traceback.format_exc())
271 elif end_type is not 'abort':
272 error_dialog(_('Could not get more books'), xhr.error_html)
273
274
275 def get_more_books():
276 data = {'offset': book_list_data.shown_book_ids.length}
277 for key in 'query', 'sort', 'sort_order', 'vl':
278 data[key] = library_data.search_result[key]
279 book_list_data.fetching_more_books = ajax_send(
280 'interface-data/more-books', data, got_more_books,
281 query={'library_id': loaded_books_query().library_id}
282 )
283 update_fetching_status()
284
285
286 def create_more_button(more):
287 more.appendChild(create_button(
288 _('Show more books'), 'cloud-download', get_more_books
289 ))
290 more.lastChild.setAttribute('rel', 'next')
291 set_css(more.firstChild, display='block', margin_left='auto', margin_right='auto', margin_top='1rem')
292 set_css(more, font_size='1.5rem', padding_top='1.5rem', margin_bottom='1.5rem', text_align='center', display='flex')
293 more.appendChild(E.div(
294 create_spinner(), '\xa0' + _('Fetching metadata for more books, please wait') + '…',
295 style='margin-left:auto; margin-right:auto; display:none')
296 )
297 update_fetching_status()
298
299
300 # }}}
301
302
303 def replace_books_page(data):
304 # Replace the current page (do not accumulate)
305 for key in data.metadata:
306 library_data.metadata[key] = data.metadata[key]
307 library_data.previous_book_ids = []
308 library_data.search_result = data.search_result
309 book_list_data.shown_book_ids = set()
310 clear_grid()
311 render_ids(data.search_result.book_ids)
312
313
314 def fetch_books_page(new_offset, page_size, on_done):
315 sr = library_data.search_result
316 if not sr:
317 if on_done:
318 on_done(False)
319 return
320 abort_get_more_books(True)
321 payload = {'offset': new_offset}
322 for key in 'query', 'sort', 'sort_order', 'vl':
323 payload[key] = sr[key]
324 book_list_data.fetching_more_books = ajax_send(
325 'interface-data/more-books', payload, def (end_type, xhr, event):
326 book_list_data.fetching_more_books = None
327 if end_type is 'load':
328 try:
329 data = JSON.parse(xhr.responseText)
330 if not data.search_result.book_ids:
331 raise Exception('No books ids object in search result from server')
332 replace_books_page(data)
333 if on_done:
334 on_done(True)
335 except Exception:
336 if on_done:
337 on_done(False)
338 elif end_type is not 'abort':
339 if on_done:
340 on_done(False)
341 ,
342 query = {'library_id': loaded_books_query().library_id, 'num': str(page_size)}
343 )
344
345
346 def fts():
347 q = {'restricted': 'y', 'restriction': library_data.search_result.query}
348 show_panel('fts', q)
349
350
351 def save_to_saved_virtual_library():
352 current_query = loaded_books_query()
353 current_search = (current_query.search or '') + ''
354 library_id = current_query.library_id or current_library_id()
355 virtual_library = (current_query.vl or '') + ''
356
357 def do_save(item):
358 if not save_saved_virtual_library(item):
359 return False
360 refresh_sidebar_navigation()
361 return True
362
363 show_saved_virtual_library_dialog(
364 _('Save as virtual library'), _('Save'), do_save,
365 library_id,
366 virtual_library,
367 initial_search=current_search,
368 )
369
370
371 def icon_action(icon_name, tooltip, action):
372 return E.a(
373 svgicon(icon_name),
374 class_='calibre-icon-button',
375 style='margin-left: 0.4em',
376 href='javascript:void(0)',
377 title=tooltip,
378 onclick=def (evt):
379 evt.preventDefault()
380 action()
381 )
382
383
384 def show_top_message(container):
385 q = loaded_books_query()
386 if not q.search and not q.vl:
387 return False
388 if q.vl:
389 container.appendChild(E.span(
390 E.span(E.span(_('Showing Virtual library: {}').format(q.vl)), E.span(_('Virt. lib: {}').format(q.vl)),
391 create_button(_('Close'), 'close', def (): show_vl();, _('Show all books in library')),
392 class_='calibre-showing-label',
393 )))
394 if q.search:
395 container.appendChild(E.br())
396 if q.search:
397 c = E.span()
398 if library_data.search_result.total_num:
399 c.style.display = 'inline-flex'
400 c.style.flexWrap = 'wrap'
401 c.style.alignItems = 'center'
402 c.style.justifyContent = 'space-between'
403 c.style.width = '100%'
404 c.appendChild(E.span(
405 E.span(_('Showing books matching:')), E.span(_('Matching:')), ' ', E.i(library_data.search_result.query),
406 class_='calibre-showing-label',
407 ))
408 buttons = E.div(style='margin-left: auto; display: inline-flex')
409 buttons.appendChild(E.span(' ', icon_action('close', _('Clear search'), def (): search();)))
410 buttons.appendChild(E.span(' ', icon_action('plus', _('Save as virtual library'), save_to_saved_virtual_library)))
411 c.appendChild(buttons)
412 if library_data.fts_enabled:
413 buttons.appendChild(E.span(' ', icon_action('search', _('Search the text of these books'), fts)))
414 else:
415 c.appendChild(E.span(_('No books matching:'), ' ', E.i(library_data.search_result.query)))
416
417 container.appendChild(c)
418 return True
419
420
421 def clear_book_list_inner(inner):
422 if inner:
423 clear(inner)
424
425
426 def create_optional_cover_grid_size_control(mode):
427 try:
428 return create_cover_grid_size_control(mode)
429 except Exception as err:
430 console.warn('Failed to create cover grid size toolbar control')
431 console.warn(err)
432
433
434 def populate_book_list_toolbar(toolbar_el, include_sort, on_view_mode_change=None, initial_mode=None):
435 if not toolbar_el:
436 return
437 clear(toolbar_el)
438 cover_grid_size_control = None
439 current_mode = initial_mode or get_view_mode()
440 mode_wrap, mode_sel = create_select(
441 _('Change book list mode'), current_mode, cover_grid=_('Cover grid'),
442 details_list=_('Detailed list'), custom_list=_('Custom list'))
443 mode_sel.dataset.currentMode = current_mode
444 mode_sel.addEventListener('change', def (ev):
445 requested_mode = mode_sel.value
446 current_mode = mode_sel.dataset.currentMode
447 if requested_mode and requested_mode is not current_mode:
448 get_session_data().set('view_mode', requested_mode)
449 if on_view_mode_change:
450 current_mode = on_view_mode_change(requested_mode) or requested_mode
451 else:
452 current_mode = apply_view_mode(requested_mode) or requested_mode
453 mode_sel.dataset.currentMode = current_mode
454 mode_sel.value = current_mode
455 if cover_grid_size_control:
456 sync_cover_grid_size_control(cover_grid_size_control, current_mode)
457 )
458 toolbar_el.appendChild(mode_wrap)
459 cover_grid_size_control = create_optional_cover_grid_size_control(current_mode)
460 if cover_grid_size_control:
461 toolbar_el.appendChild(cover_grid_size_control)
462 if not include_sort:
463 return
464
465 def toggle_sort_order(ev=None):
466 _csf, _csfo = current_sorted_field()
467 if _csf is 'date':
468 _csf = 'timestamp'
469 new_order = 'desc' if _csfo is 'asc' else 'asc'
470 if _csf:
471 change_sort(_csf, new_order)
472
473 try:
474 if not library_data.sortable_fields:
475 return
476 csf, csfo = current_sorted_field()
477 if csf is 'date':
478 csf = 'timestamp'
479 found = False
480 options = {}
481 for field, name in library_data.sortable_fields:
482 options[field] = name
483 if field is csf:
484 found = True
485 if not found and library_data.sortable_fields?.length:
486 value = library_data.sortable_fields[0][0]
487 else:
488 value = csf
489 sort_wrap, sort_field_sel = create_select(_('Change how the list is sorted'), value, **options)
490 sort_field_sel.addEventListener('change', def (ev):
491 f = sort_field_sel.value or ''
492 if f:
493 change_sort(f, None)
494 )
495 toolbar_el.appendChild(sort_wrap)
496
497 icon_name = 'sort-amount-asc' if (csfo or 'asc') is 'asc' else 'sort-amount-desc'
498 toolbar_el.appendChild(create_button('', icon=icon_name, action=toggle_sort_order, tooltip=_('Toggle sort order'), class_='cs-sort-order-btn'))
499 except Exception:
500 pass
501
502
503 def create_books_list(container):
504 book_list_data.container_id = ensure_id(container)
505 book_list_data.shown_book_ids = set()
506 book_list_data.mode = None
507 abort_get_more_books(True)
508 pager = E.div(data_component='pager')
509 book_list_div = E.div(data_component='book_list')
510 bottom_pager_el = E.div(style='margin-bottom:1.5rem')
511 single_page_count_el = E.div(style='margin: 0.5ex 0')
512 container.appendChild(pager)
513 container.appendChild(single_page_count_el)
514 container.appendChild(book_list_div)
515 container.appendChild(bottom_pager_el)
516 top_widget = create_pager_widget(
517 def (): go_to_offset((library_data.search_result.offset or 0) - page_size);,
518 def (): go_to_offset((library_data.search_result.offset or 0) + page_size);,
519 )
520 bottom_widget = create_pager_widget(
521 def (): go_to_offset((library_data.search_result.offset or 0) - page_size);,
522 def (): go_to_offset((library_data.search_result.offset or 0) + page_size);,
523 )
524 bottom_pager_el.appendChild(bottom_widget.container)
525
526 top_widget.set_top_row_visibility(show_top_message(top_widget.top_row))
527 apply_view_mode(get_view_mode())
528
529 q = parse_url_params()
530 page_size = clamp(parse_int(q.num, library_data.search_result?.num or 50), 10, 200)
531
532 def go_to_offset(new_offset):
533 new_offset = max(0, new_offset)
534 qq = parse_url_params()
535 qq.offset = str(new_offset)
536 qq.num = str(page_size)
537 push_state(qq, replace=True, call_handler=False)
538 fetch_books_page(new_offset, page_size, def (ok):
539 if not ok:
540 error_dialog(_('Could not load books'), _('Failed to load the requested page'))
541 update_pager()
542 )
543
544 def update_pager():
545 sr = library_data.search_result
546 total = sr.total_num or 0
547 offset = sr.offset or 0
548 end = min(total, offset + page_size)
549 top_widget.count_msg.textContent = _('{0}–{1} of {2}').format((offset + 1) if total else 0, end, total)
550 has_prev = offset > 0
551 has_next = end < total
552 top_widget.set_enabled(has_prev, has_next)
553 bottom_widget.set_enabled(has_prev, has_next)
554 if not has_prev and not has_next and total and loaded_books_query().search:
555 single_page_count_el.textContent = ngettext('{} book found', '{} books found', total).format(total)
556 else:
557 single_page_count_el.textContent = ''
558
559 update_pager()
560 pager.appendChild(top_widget.container)
561 populate_book_list_toolbar(top_widget.middle_row, True)
562 top_widget.set_middle_row_visibility(top_widget.middle_row.children.length > 0)
563
564 q = parse_url_params()
565 scrolled = False
566 if q.book_id:
567 e = container.querySelector(f'.{ITEM_CLASS_NAME}[data-book-id="{q.book_id}"]')
568 if e and e.scrollIntoView:
569 e.scrollIntoView(True)
570 # Now scroll extra corresponding to top bar size
571 window.scrollBy(0, -container.offsetTop)
572 scrolled = True
573 if not scrolled:
574 window.scrollTo(0, 0)
575 q = loaded_books_query()
576 if not q.search and library_data.search_result.total_num < 1:
577 book_list_div.appendChild(E.div(_('No books found'), style='margin: 1ex 0'))
578
579
580 def check_for_books_loaded():
581 container = this
582 container_id = container.id
583 if load_status.loading:
584 conditional_timeout(container_id, 5, check_for_books_loaded)
585 return
586 container = container.lastChild
587 if not load_status.ok:
588 clear(container)
589 if load_status.http_error_code is 401:
590 # Unauthorized, keep retrying until the user provides a
591 # username/password
592 container.appendChild(E.div(_('Username/password required, retrying...')))
593 ensure_current_library_data()
594 conditional_timeout(container_id, 100, check_for_books_loaded)
595 return
596 err = E.div()
597 safe_set_inner_html(err, load_status.error_html)
598 container.appendChild(E.div(
599 style='margin: 1ex 1em',
600 E.div(_('Failed to load books from calibre library, with error:')),
601 err,
602 E.div(
603 style='margin-top: 1em; border-top: solid 1px currentColor; padding-top: 1ex;',
604 E.a(onclick=def (): home(replace=True);, href='javascript: void(0)', class_='blue-link', _('Go back to the home page')))
605 ),
606 )
607 return
608 clear_book_list_inner(container)
609 create_books_list(container)
610 # If the URL specifies an offset, show that page
611 q = parse_url_params()
612 desired_offset = max(0, parse_int(q.offset, 0))
613 if desired_offset:
614 page_size = clamp(parse_int(q.num, library_data.search_result?.num or 50), 10, 200)
615 fetch_books_page(desired_offset, page_size, def (ok):
616 pass
617 )
618 if library_data.search_result and jstype(library_data.search_result.num_books_without_search) is 'number':
619 set_title_tooltip(this, _('Total number of books: {}').format(library_data.search_result.num_books_without_search))
620
621
622 def init(container_id):
623 interface_data = get_interface_data()
624 ensure_current_library_data()
625 container = document.getElementById(container_id)
626 lid = container.dataset.library_id = url_books_query().library_id
627 title = interface_data.library_map[lid]
628 update_window_title(title)
629 create_top_bar(container, title=title, action=def (): save_scroll_position(), home();, icon='home')
630 add_book_list_top_bar_buttons(container)
631
632 inner = E.div(class_=CLASS_NAME)
633 container.appendChild(inner)
634 inner.appendChild(E.div(_('Loading books from the {} calibre library, please wait...').format(title), style='margin: 1ex 1em'))
635 conditional_timeout(container_id, 5, check_for_books_loaded)
636
637
638 # Sorting {{{
639
640
641 def change_sort(field, order):
642 abort_get_more_books()
643 sd = get_session_data()
644 so = sd.get('last_sort_order')
645 order = order or so[field] or 'asc'
646 order = 'asc' if order is 'asc' else 'desc'
647 q = loaded_books_query()
648 q.sort = field + '.' + order
649 so[field] = order
650 sd.set('last_sort_order', so)
651 sd.set_library_option(q.library_id, 'sort', q.sort)
652 show_panel('book_list', query=q, replace=True)
653
654
655 def create_sort_panel(container_id):
656 if not library_data.sortable_fields:
657 show_panel('book_list', replace=True)
658 return
659 container = document.getElementById(container_id)
660 close_action, close_icon = back, 'close'
661 if parse_url_params().close_action is 'home':
662 close_action, close_icon = def (): home();, 'home'
663 create_top_bar(container, title=_('Sort books by…'), action=close_action, icon=close_icon)
664 items = []
665 csf, csf_order = current_sorted_field()
666 new_sort_order = 'desc' if csf_order is 'asc' else 'asc'
667 if csf is 'date':
668 csf = 'timestamp'
669 for field, name in library_data.sortable_fields:
670 subtitle = icon_name = None
671 if field is csf:
672 subtitle = _('Reverse current sort order')
673 icon_name = 'sort-amount-asc' if csf_order is 'asc' else 'sort-amount-desc'
674 action = change_sort.bind(None, field, new_sort_order)
675 else:
676 action = change_sort.bind(None, field, None)
677 items.push(create_item(name, subtitle=subtitle, icon=icon_name, action=action))
678 container.appendChild(E.div())
679 create_item_list(container.lastChild, items, _('Change how the list of books is sorted'))
680 enable_escape_key(container, close_action)
681 # }}}
682
683 # Searching {{{
684
685
686 def search_query_for(query):
687 q = loaded_books_query()
688 if query:
689 q.search = query
690 else:
691 v'delete q.search'
692 return q
693
694
695 def search(query, replace=False):
696 show_panel('book_list', query=search_query_for(query), replace=replace)
697
698 set_apply_search(def (query): search(query, True);)
699
700 # }}}
701
702
703 # Virtual libraries {{{
704 def create_vl_panel(container_id):
705 if not library_data.sortable_fields:
706 show_panel('book_list', replace=True)
707 return
708 container = document.getElementById(container_id)
709 create_top_bar(container, title=_('Choose Virtual library…'), icon='back')
710 items = []
711 vls = all_virtual_libraries()
712 vl_names = Object.keys(vls).sort(def (a, b): return a.toLowerCase().localeCompare(b.toLowerCase());)
713 for name in vl_names:
714 items.push(create_item(name, subtitle=vls[name], action=show_vl.bind(None, name, True)))
715 container.appendChild(E.div())
716 create_item_list(container.lastChild, items, _('Choose a Virtual library to browse from the list below'))
717 enable_escape_key(container, back)
718
719
720 def show_vl(vl_name, replace):
721 q = loaded_books_query()
722 q.vl = vl_name or None
723 show_panel('book_list', query=q, replace=replace or False)
724
725 # }}}
726
727
728 # Modes {{{
729 def create_mode_panel(container_id):
730 if not library_data.sortable_fields:
731 show_panel('book_list', replace=True)
732 return
733 container = document.getElementById(container_id)
734 create_top_bar(container, title=_('Choose book list mode…'), icon='back')
735 items = []
736 current_mode = get_view_mode()
737
738 def ci(title, desc, name):
739 ic = 'check' if name is current_mode else None
740 items.push(create_item(title, subtitle=desc, icon=ic, action=def ():
741 if name is not current_mode:
742 get_session_data().set('view_mode', name)
743 back()
744 ))
745
746 ci(_('Cover grid'), COVER_GRID_DESCRIPTION(), 'cover_grid')
747 ci(_('Detailed list'), DETAILS_LIST_DESCRIPTION(), 'details_list')
748 ci(_('Custom list'), CUSTOM_LIST_DESCRIPTION(), 'custom_list')
749 container.appendChild(E.div())
750 create_item_list(container.lastChild, items, _('Choose a display mode for the list of books from below'))
751 enable_escape_key(container, back)
752
753 # }}}
754
755
756 # Adding books {{{
757 def create_add_panel(container_id):
758 if not library_data.sortable_fields:
759 show_panel('book_list', replace=True)
760 return
761 add_books_panel(container_id)
762
763 # }}}
764
765
766 def set_panel_handlers():
767 set_panel_handler('book_list', init)
768 set_panel_handler('book_list^add', create_add_panel)
769 set_panel_handler('book_list^sort', create_sort_panel)
770 set_panel_handler('book_list^vl', create_vl_panel)
771 set_panel_handler('book_list^search', init_search_panel)
772 set_panel_handler('book_list^choose_mode', create_mode_panel)
773 set_panel_handler('book_list^search^prefs', tb_config_panel_handler())