Debian Codegraph @

src/pyj/file_uploads.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 from elementmaker import E
6 from gettext import gettext as _
7
8 from dom import ensure_id
9 from utils import human_readable, safe_set_inner_html
10
11
12 def upload_files_widget(container, proceed, msg, single_file=False, accept_extensions=None):
13 container_id = ensure_id(container, 'upload-files')
14
15 def files_selected():
16 files = this.files
17 if c.parentNode:
18 c.parentNode.removeChild(c)
19 if callable(proceed) and files.length:
20 proceed(container_id, files)
21
22 msg = msg or _('Upload books by either <a>selecting the book files</a> or drag and drop the files here')
23 c = E.div(
24 class_='cs-upload-dropzone',
25 E.span(class_='cs-upload-dropzone-msg'),
26 E.input(type='file', class_='cs-upload-file-input', style='display:none', onchange=files_selected),
27 )
28 if not single_file:
29 c.lastChild.setAttribute('multiple', 'multiple')
30 if accept_extensions:
31 c.lastChild.setAttribute('accept', ', '.join(['.' + x for x in accept_extensions.split(' ')]))
32
33 safe_set_inner_html(c.firstChild, msg)
34 a = c.getElementsByTagName('a')[0]
35 a.setAttribute('href', 'javascript: void(0)')
36 a.classList.add('blue-link')
37 a.addEventListener('click', def ():
38 document.getElementById(container_id).querySelector('input[type=file]').click()
39 , False)
40
41 def pick_if_not_link(ev):
42 t = ev.target
43 if t and t.tagName.toLowerCase() is 'a':
44 return
45 inp = document.getElementById(container_id).querySelector('.cs-upload-file-input')
46 if inp:
47 inp.click()
48
49 c.addEventListener('click', pick_if_not_link, False)
50 container.appendChild(c)
51
52 def stop(e):
53 e.stopPropagation(), e.preventDefault()
54
55 def drop(e):
56 stop(e)
57 dt = e.dataTransfer
58 files_selected.call(dt)
59
60 c.addEventListener('dragenter', stop, False)
61 c.addEventListener('dragover', stop, False)
62 c.addEventListener('drop', drop, False)
63 return c
64
65
66 def update_status_widget(w, sent, total):
67 if total:
68 p = w.getElementsByTagName('progress')[0]
69 p.setAttribute('value', '' + sent)
70 p.setAttribute('max', '' + total)
71 w.lastChild.textContent = _(' {percent:.0%} of {total}').format(percent=sent / total, total=human_readable(total))
72
73
74 def upload_status_widget(name, job_id):
75 ans = E.div(class_='cs-upload-job', data_job='' + job_id)
76 if name:
77 ans.appendChild(E.h3(E.b(name), class_='cs-upload-job-title'))
78 ans.appendChild(E.progress(class_='cs-upload-progress'))
79 ans.appendChild(E.span(class_='cs-upload-progress-label'))
80 return ans