Debian Codegraph @

src/pyj/modals.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 from elementmaker import E
6 from gettext import gettext as _
7
8 from ajax import ajax, ajax_send
9 from book_list.globals import get_session_data
10 from book_list.theme import get_color, get_font_size
11 from dom import add_extra_css, build_rule, clear, set_css, svgicon, unique_id
12 from popups import MODAL_Z_INDEX
13 from utils import safe_set_inner_html
14 from widgets import create_button
15
16 modal_container = None
17 modal_count = 0
18
19 add_extra_css(def ():
20 modal_max = 'min(48rem, calc(100vw - 2rem))'
21 style = build_rule(
22 '#modal-container > div > a:hover',
23 color=get_color('dialog-foreground') + ' !important',
24 background_color=get_color('dialog-background') + ' !important'
25 )
26 style += build_rule(
27 '#modal-container',
28 overflow_x='auto',
29 overflow_y='auto',
30 overscroll_behavior_x='none',
31 overscroll_behavior_y='contain',
32 touch_action='pan-x pan-y',
33 padding=(
34 'max(1rem, env(safe-area-inset-top, 0px)) max(1rem, env(safe-area-inset-right, 0px))'
35 ' max(1rem, env(safe-area-inset-bottom, 0px)) max(1rem, env(safe-area-inset-left, 0px))'
36 ),
37 box_sizing='border-box',
38 )
39 style += build_rule(
40 '#modal-container > div',
41 # Must not clip the absolutely positioned close control (it sits slightly outside the box)
42 overflow_x='visible',
43 overflow_y='visible',
44 width='max-content',
45 min_width='0',
46 max_width=modal_max,
47 box_sizing='border-box',
48 )
49 style += build_rule(
50 '.modal_height_container',
51 min_width='0',
52 max_width='100%',
53 overflow_wrap='anywhere',
54 word_break='break-word',
55 overflow_x='auto',
56 overflow_y='auto',
57 overscroll_behavior_x='none',
58 touch_action='pan-x pan-y',
59 )
60 style += build_rule(
61 '#modal-container .modal_height_container pre, #modal-container .modal_height_container code',
62 white_space='pre-wrap',
63 overflow_wrap='anywhere',
64 word_break='break-word',
65 )
66 style += build_rule(
67 '#modal-container .modal_height_container img, #modal-container .modal_height_container iframe',
68 max_width='100%',
69 height='auto',
70 )
71 style += build_rule(
72 '#modal-container .modal_height_container table',
73 max_width='100%',
74 box_sizing='border-box',
75 )
76 style += build_rule(
77 '#modal-container .modal_height_container th, #modal-container .modal_height_container td',
78 overflow_wrap='anywhere',
79 word_break='break-word',
80 )
81 style += build_rule(
82 '#modal-container .modal_height_container input:not([type="checkbox"]):not([type="radio"]):not([type="color"]):not([type="file"]),' +
83 '#modal-container .modal_height_container textarea, #modal-container .modal_height_container select',
84 max_width='100%',
85 box_sizing='border-box',
86 )
87 style += build_rule(
88 '#modal-container .button-box',
89 display='flex', justify_content='space-between', align_items='stretch',
90 flex_wrap='wrap', gap='0.5rem',
91 padding='1rem 0rem', min_width='0',
92 )
93 style += build_rule(
94 '#modal-container .button-box > a.calibre-push-button',
95 flex='1 1 0', min_width='0', justify_content='center',
96 )
97 style += build_rule(
98 '#modal-container .button-box > a.calibre-push-button:only-of-type',
99 flex='0 1 auto', margin_left='auto',
100 )
101 style += build_rule(
102 '#modal-container .button-box.button-box--wrap-chips',
103 justify_content='flex-start',
104 )
105 style += build_rule(
106 '#modal-container .button-box.button-box--wrap-chips > a.calibre-push-button',
107 flex='0 1 auto',
108 )
109 style += build_rule(
110 '#modal-container > div > a:last-child',
111 z_index='2',
112 )
113 return style
114 )
115
116
117 class Modal:
118 def __init__(self, create_func, on_close, show_close, onkeydown):
119 nonlocal modal_count
120 self.create_func, self.on_close, self.show_close = create_func, on_close, show_close
121 self.onkeydown = onkeydown
122 modal_count += 1
123 self.id = modal_count
124
125
126 class ModalContainer:
127 def __init__(self):
128 div = E.div(id='modal-container', tabindex='0',
129 E.div( # popup
130 E.div(class_='modal_height_container'), # content area
131 E.a(svgicon('close'), title=_('Close'), onclick=self.close_current_modal.bind(self))
132 )
133 )
134 div.addEventListener('keydown', self.onkeydown.bind(self), {'passive': False})
135 document.body.appendChild(div)
136
137 # Container style
138 set_css(div,
139 position='fixed', top='0', right='0', bottom='0', left='0', # Stretch over entire window
140 background_color='rgba(0,0,0,0.5)', backdrop_filter='blur(2px)', webkit_backdrop_filter='blur(2px)',
141 z_index=MODAL_Z_INDEX + '',
142 display='none', user_select='none', justify_content='center', align_items='center',
143 overscroll_behavior_x='none', overscroll_behavior_y='contain',
144 )
145
146 # Popup style (no background gradient — solid dialog-background for readability)
147 popup_max = 'min(48rem, calc(100vw - 2rem))'
148 set_css(div.firstChild,
149 position='relative', display='inline-block',
150 min_width='min(16rem, calc(100vw - 2rem))', max_width=popup_max,
151 overflow_x='visible', overflow_y='visible', box_sizing='border-box',
152 border_radius='1em', padding='1em 2em', margin_right='1em', margin_left='1em',
153 background_color=get_color('dialog-background'),
154 color=get_color('dialog-foreground'),
155 background_image=get_color('dialog-background-image'),
156 box_shadow='0 12px 40px rgba(0,0,0,0.2)',
157 border='var(--calibre-border-style)',
158 )
159
160 # Close button style
161 set_css(div.firstChild.lastChild,
162 font_size='1.5em', line_height='100%', cursor='pointer', position='absolute',
163 right='-0.5em', top='-0.5em', width='1em', height='1em',
164 background_color=get_color('window-foreground'), color=get_color('window-background'), display='inline-box',
165 border_radius='50%', padding='4px', text_align='center', box_shadow='1px 1px 3px black',
166 z_index='2',
167 )
168 # Content container style
169 # need padding: 1px to avoid scrollbar in modal on Qt WebEngine 6.3
170 set_css(div.firstChild.firstChild, user_select='text', max_height='min(60vh, calc(100vh - 6rem))',
171 overflow_x='auto', overflow_y='auto', overscroll_behavior_x='none', padding='1px', min_width='0', max_width='100%')
172
173 self.modals = []
174 self.current_modal = None
175 self.hide = self.close_current_modal.bind(self)
176
177 @property
178 def modal_container(self):
179 return document.getElementById('modal-container')
180
181 def show_modal(self, create_func, on_close=None, show_close=True, onkeydown=None):
182 self.modals.push(Modal(create_func, on_close, show_close, onkeydown))
183 modal_id = self.modals[-1].id
184 self.update()
185 window.setTimeout(def (): self.modal_container.focus();, 0)
186 return modal_id
187
188 def hide_modal(self, modal_id):
189 if self.current_modal is not None and self.current_modal.id is modal_id:
190 self.clear_current_modal()
191 else:
192 doomed_modal = None
193 for i, modal in enumerate(self.modals):
194 if modal.id is modal_id:
195 doomed_modal = i
196 break
197 if doomed_modal is not None:
198 self.modals.splice(doomed_modal, 1)
199
200 def update(self):
201 if self.current_modal is None and self.modals:
202 self.current_modal = self.modals.shift()
203 c = self.modal_container
204 try:
205 self.current_modal.create_func(c.firstChild.firstChild, self.hide)
206 except:
207 self.current_modal = None
208 raise
209 if c.style.display is 'none':
210 c.style.display = 'flex'
211 c.firstChild.lastChild.style.visibility = 'visible' if self.current_modal.show_close else 'hidden'
212
213 def clear_current_modal(self):
214 self.current_modal = None
215 c = self.modal_container
216 clear(c.firstChild.firstChild)
217 if self.modals.length is 0:
218 set_css(c, display='none')
219 else:
220 self.update()
221
222 def close_current_modal(self, event):
223 if self.current_modal is not None:
224 if self.current_modal.on_close is not None and self.current_modal.on_close(event) is True:
225 return
226 self.clear_current_modal()
227
228 def close_all_modals(self):
229 while self.current_modal is not None:
230 self.close_current_modal()
231
232 def onkeydown(self, event):
233 if self.current_modal is not None and self.current_modal.onkeydown:
234 return self.current_modal.onkeydown(event, self.clear_current_modal.bind(self))
235 if (event.key is 'Escape' or event.key is 'Esc') and not event.altKey and not event.ctrlKey and not event.metaKey and not event.shiftKey:
236 event.preventDefault(), event.stopPropagation()
237 self.close_current_modal(event)
238
239
240 def create_simple_dialog_markup(title, msg, details, icon, prefix, icon_color, parent):
241 details = details or ''
242 show_details = E.a(class_='blue-link', style='padding-top:1em; display:inline-block; margin-left: auto', _('Show details'))
243 show_details.addEventListener('click', def ():
244 show_details.style.display = 'none'
245 show_details.nextSibling.style.display = 'block'
246 )
247 is_html_msg = /<[a-zA-Z]/.test(msg)
248 html_container = E.div()
249 if is_html_msg:
250 safe_set_inner_html(html_container, msg)
251 details_container = E.span()
252 if /<[a-zA-Z]/.test(details):
253 safe_set_inner_html(details_container, details)
254 else:
255 details_container.textContent = details
256 if prefix:
257 prefix = E.span(' ' + prefix + ' ', style='white-space:pre; font-variant: small-caps')
258 else:
259 prefix = '\xa0'
260 parent.appendChild(E.div(
261 style='max-width:100%; min-width:0; box-sizing:border-box; text-align:left; overflow-wrap:anywhere; word-break:break-word',
262 E.h2(
263 E.span(svgicon(icon), style=f'color:{icon_color}'), prefix, title,
264 style='font-weight: bold; font-size: ' + get_font_size('title') + '; overflow-wrap:anywhere; word-break:break-word',
265 ),
266 E.div(
267 (html_container if is_html_msg else msg),
268 style='padding-top: 1em; margin-top: 1em; border-top: 1px solid currentColor; min-width:0; overflow-wrap:anywhere; word-break:break-word',
269 ),
270 E.div(
271 style='display: ' + ('block' if details else 'none'),
272 show_details,
273 E.div(details_container,
274 style='display:none; white-space:pre-wrap; font-size: smaller; margin-top: 1em; border-top: solid 1px currentColor; padding-top: 1em'),
275 ),
276 ))
277
278
279 def create_simple_dialog(title, msg, details, icon, prefix, on_close=None, icon_color='red'):
280 show_modal(create_simple_dialog_markup.bind(None, title, msg, details, icon, prefix, icon_color), on_close=on_close)
281
282
283 def create_custom_dialog(title, content_generator_func, on_close=None, onkeydown=None):
284 def create_func(parent, close_modal):
285 content_div = E.div()
286 parent.appendChild(
287 E.div(
288 style='max-width:100%; min-width:0; box-sizing:border-box; text-align:left; overflow-wrap:anywhere; word-break:break-word',
289 E.h2(title, style='font-weight: bold; font-size: ' + get_font_size('title') + '; overflow-wrap:anywhere; word-break:break-word'),
290 E.div(content_div, style='padding-top: 1em; margin-top: 1em; border-top: 1px solid currentColor; min-width:0'),
291 ))
292 content_generator_func(content_div, close_modal)
293 show_modal(create_func, on_close=on_close, onkeydown=onkeydown)
294
295
296 def get_text_dialog(title, callback, initial_text=None, msg=None, rows=12):
297 called = {}
298 cid = unique_id()
299
300 def keyaction(ok, close_modal):
301 if called.done:
302 return
303 called.done = True
304 text = document.getElementById(cid).value or ''
305 if close_modal:
306 close_modal()
307 callback(ok, text)
308
309 def on_keydown(event, close_modal):
310 if event.altKey or event.ctrlKey or event.metaKey or event.shiftKey:
311 return
312 if event.key is 'Escape' or event.key is 'Esc':
313 event.preventDefault(), event.stopPropagation()
314 keyaction(False, close_modal)
315
316 create_custom_dialog(
317 title, def (parent, close_modal):
318 parent.appendChild(E.div(
319 E.textarea(initial_text or '', placeholder=msg or '', id=cid, rows=rows + '',
320 style='width:100%; max-width:100%; min-width:0; box-sizing:border-box; resize:vertical'),
321 E.div(class_='button-box',
322 create_button(_('Cancel'), 'close', keyaction.bind(None, False, close_modal)),
323 create_button(_('OK'), 'check', keyaction.bind(None, True, close_modal), highlight=True),
324 ),
325 ))
326 window.setTimeout(def (): parent.querySelector('textarea').focus();, 10)
327 ,
328 on_close = keyaction.bind(None, False, None),
329 onkeydown = on_keydown
330 )
331
332
333 def question_dialog(
334 title, msg, callback, yes_text=None, no_text=None,
335 skip_dialog_name=None, skip_dialog_msg=None,
336 skip_dialog_skipped_value=True, skip_dialog_skip_precheck=True,
337 ):
338 yes_text = yes_text or _('Yes')
339 no_text = no_text or _('No')
340 called = {}
341
342 def keyaction(yes, close_modal):
343 if called.done:
344 return
345 called.done = True
346 if skip_dialog_name:
347 if not skip_box.querySelector('input').checked:
348 sd = get_session_data()
349 skipped_dialogs = Object.assign(v'{}', sd.get('skipped_dialogs', v'{}'))
350 skipped_dialogs[skip_dialog_name] = Date().toISOString()
351 sd.set('skipped_dialogs', skipped_dialogs)
352 if close_modal:
353 close_modal()
354 callback(yes)
355
356 def on_keydown(event, close_modal):
357 if event.altKey or event.ctrlKey or event.metaKey or event.shiftKey:
358 return
359 if event.key is 'Escape' or event.key is 'Esc':
360 event.preventDefault(), event.stopPropagation()
361 keyaction(False, close_modal)
362 if event.key is 'Enter' or event.key is 'Return' or event.key is 'Space':
363 event.preventDefault(), event.stopPropagation()
364 keyaction(True, close_modal)
365
366 skip_box = E.div(style='margin-top: 2ex;')
367 if skip_dialog_name:
368 sd = get_session_data()
369 skipped_dialogs = sd.get('skipped_dialogs', v'{}')
370 if skipped_dialogs[skip_dialog_name]:
371 return callback(skip_dialog_skipped_value)
372 skip_dialog_msg = skip_dialog_msg or _('Show this confirmation again')
373 skip_box.appendChild(E.label(E.input(type='checkbox', name='skip_dialog'), '\xa0', skip_dialog_msg))
374 if skip_dialog_skip_precheck:
375 skip_box.querySelector('input').checked = True
376 else:
377 skip_box.style.display = 'none'
378
379 create_custom_dialog(
380 title, def (parent, close_modal):
381 parent.appendChild(E.div(
382 E.div(msg),
383 skip_box,
384 E.div(class_='button-box',
385 create_button(no_text, 'close', keyaction.bind(None, False, close_modal)),
386 create_button(yes_text, 'check', keyaction.bind(None, True, close_modal), highlight=True),
387 ))
388 )
389 ,
390 on_close = keyaction.bind(None, False, None),
391 onkeydown = on_keydown
392 )
393
394
395 def create_progress_dialog(msg, on_close):
396 msg = msg or _('Loading, please wait...')
397 pbar, msg_div = E.progress(style='display:inline-block'), E.div(msg, style='text-align:center; padding-top:1ex')
398
399 def create_func(parent):
400 parent.appendChild(E.div(style='text-align: center; max-width:100%; min-width:0; box-sizing:border-box', pbar, msg_div))
401 show_close = on_close is not None
402 modal_id = show_modal(create_func, on_close, show_close)
403 return {
404 'close': def (): modal_container.hide_modal(modal_id);,
405 'update_progress': def (amount, total): pbar.max, pbar.value = total, amount;,
406 'set_msg': def (new_msg): safe_set_inner_html(msg_div, new_msg);,
407 }
408
409 # def test_progress():
410 # counter = 0
411 # pd = progress_dialog('Testing progress dialog, please wait...', def():
412 # nonlocal counter
413 # counter = 101
414 # console.log('pd canceled')
415 # )
416 # def update():
417 # nonlocal counter
418 # counter += 1
419 # pd.update_progress(counter, 100)
420 # if counter < 100:
421 # setTimeout(update, 150)
422 # else:
423 # pd.close()
424 # update()
425 #
426 # def test_error():
427 # error_dialog(
428 # 'Hello, world!',
429 # 'Some long text to test rendering/line breaking in error dialogs that contain lots of text'
430 # ' like this test error dialog from hell in a handbasket with fruits and muppets making a scene.',
431 # ['a word ' for i in range(10000)].join(' ')
432 # )
433
434
435 def create_modal_container():
436 nonlocal modal_container
437 if modal_container is None:
438 modal_container = ModalContainer()
439 # window.setTimeout(def():
440 # document.getElementById('books-view-1').addEventListener('click', test_progress)
441 # , 10)
442 return modal_container
443
444
445 def show_modal(create_func, on_close=None, show_close=True, onkeydown=None):
446 return modal_container.show_modal(create_func, on_close, show_close, onkeydown)
447
448
449 def close_all_modals():
450 return modal_container.close_all_modals()
451
452
453 def error_dialog(title, msg, details=None, on_close=None):
454 create_simple_dialog(title, msg, details, 'bug', _('Error:'), on_close)
455
456
457 def warning_dialog(title, msg, details=None, on_close=None):
458 create_simple_dialog(title, msg, details, 'warning', _('Warning:'), on_close)
459
460
461 def info_dialog(title, msg, details=None, on_close=None):
462 create_simple_dialog(title, msg, details, 'check', '', on_close, icon_color='green')
463
464
465 def progress_dialog(msg, on_close=None):
466 # Show a modal dialog with a progress bar and an optional close button.
467 # If the user clicks the close button, on_close is called and the dialog is closed.
468 # Returns an object with the methods: close(), update_progress(amount, total), set_msg()
469 # Call update_progress() to update the progress bar
470 # Call set_msg() to change the displayed message
471 # Call close() once the task being performed is finished
472 return create_progress_dialog(msg, on_close)
473
474
475 def ajax_progress_dialog(path, on_complete, msg, extra_data_for_callback=None, **kw):
476 pd = None
477
478 def on_complete_callback(event_type, xhr, ev):
479 nonlocal pd
480 pd.close()
481 pd = undefined
482 return on_complete(event_type, xhr, ev)
483
484 def on_progress_callback(loaded, total, xhr):
485 pd.update_progress(loaded, total)
486 xhr = ajax(path, on_complete_callback, on_progress=on_progress_callback, **kw)
487 xhr.extra_data_for_callback = extra_data_for_callback
488 pd = progress_dialog(msg, xhr.abort.bind(xhr))
489 xhr.send()
490 return xhr, pd
491
492
493 def ajax_send_progress_dialog(path, data, on_complete, msg, **kw):
494 pd = None
495
496 def on_complete_callback(event_type, xhr, ev):
497 nonlocal pd
498 pd.close()
499 pd = undefined
500 return on_complete(event_type, xhr, ev)
501
502 def on_progress_callback(loaded, total, xhr):
503 pd.update_progress(loaded, total)
504 xhr = ajax_send(path, data, on_complete_callback, on_progress=on_progress_callback, **kw)
505 pd = progress_dialog(msg, xhr.abort.bind(xhr))
506 return xhr, pd