Debian Codegraph @

src/pyj/utils.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 encodings import hexlify
6
7 from ajax import encode_query
8 from book_list.theme import get_font_family
9
10
11 is_ios = v'!!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)'
12 ios_major_version = 0
13 if ! is_ios and v'!!navigator.platform' and window? and window.navigator.platform is 'MacIntel' and window.navigator.maxTouchPoints > 1:
14 # iPad Safari in desktop mode https://stackoverflow.com/questions/57765958/how-to-detect-ipad-and-ipad-os-version-in-ios-13-and-up
15 is_ios = True
16 if is_ios:
17 v = v'navigator.appVersion.match(/OS (\d+)/)'
18 if v and v[1]:
19 ios_major_version = parseInt(v[1], 10) or 0
20
21
22 def default_context_menu_should_be_allowed(evt):
23 if evt.target and evt.target.tagName and evt.target.tagName.toLowerCase() in ('input', 'textarea'):
24 return True
25 return False
26
27
28 def debounce(func, wait, immediate=False):
29 # Returns a function, that, as long as it continues to be invoked, will not
30 # be triggered. The function will be called after it stops being called for
31 # wait milliseconds. If `immediate` is True, trigger the function on the
32 # leading edge, instead of the trailing.
33 timeout = None
34 return def debounce_inner(): # noqa: unused-local
35 nonlocal timeout
36 context, args = this, arguments
37
38 def later():
39 nonlocal timeout
40 timeout = None
41 if not immediate:
42 func.apply(context, args)
43 call_now = immediate and not timeout
44 window.clearTimeout(timeout)
45 timeout = window.setTimeout(later, wait)
46 if call_now:
47 func.apply(context, args)
48
49 if Object.assign:
50 copy_hash = def (obj):
51 return Object.assign({}, obj)
52 else:
53 copy_hash = def (obj):
54 return {k: obj[k] for k in Object.keys(obj)}
55
56
57 def parse_url_params(url=None, allow_multiple=False):
58 cache = parse_url_params.cache
59 url = url or window.location.href
60 if cache[url]:
61 return copy_hash(parse_url_params.cache[url])
62 qs = url.indexOf('#')
63 ans = {}
64 if qs < 0:
65 cache[url] = ans
66 return copy_hash(ans)
67 q = url.slice(qs + 1, (url.length + 1))
68 if not q:
69 cache[url] = ans
70 return copy_hash(ans)
71 pairs = q.replace(/\+/g, ' ').split('&')
72 for pair in pairs:
73 key, val = pair.partition('=')[::2]
74 key, val = decodeURIComponent(key), decodeURIComponent(val)
75 if allow_multiple:
76 if ans[key] is undefined:
77 ans[key] = []
78 ans[key].append(val)
79 else:
80 ans[key] = val
81 cache[url] = ans
82 return copy_hash(ans)
83 parse_url_params.cache = {}
84
85
86 def encode_query_with_path(query, path):
87 path = path or window.location.pathname
88 return path + encode_query(query, '#')
89
90
91 def full_screen_supported(elem):
92 elem = elem or document.documentElement
93 if elem.requestFullScreen or elem.webkitRequestFullScreen or elem.mozRequestFullScreen:
94 return True
95 return False
96
97
98 def request_full_screen(elem):
99 elem = elem or document.documentElement
100 options = {'navigationUI': 'hide'}
101 if elem.requestFullScreen:
102 elem.requestFullScreen(options)
103 elif elem.webkitRequestFullScreen:
104 elem.webkitRequestFullScreen()
105 elif elem.mozRequestFullScreen:
106 elem.mozRequestFullScreen()
107
108
109 def full_screen_element():
110 return document.fullscreenElement or document.webkitFullscreenElement or document.mozFullScreenElement or document.msFullscreenElement
111
112
113 _roman = list(zip(
114 [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
115 ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
116 ))
117
118
119 def roman(num):
120 if num <= 0 or num >= 4000 or int(num) is not num:
121 return num + ''
122 result = []
123 for d, r in _roman:
124 while num >= d:
125 result.append(r)
126 num -= d
127 return result.join('')
128
129
130 def fmt_sidx(val, fmt='{:.2f}', use_roman=True):
131 if val is undefined or val is None or val is '':
132 return '1'
133 if int(val) is float(val):
134 if use_roman:
135 return roman(val)
136 return int(val) + ''
137 return fmt.format(float(val))
138
139
140 def rating_to_stars(value, allow_half_stars=False, star='★', half='⯨'):
141 r = max(0, min(int(value or 0), 10))
142 if allow_half_stars:
143 ans = star.repeat(r // 2)
144 if r % 2:
145 ans += half
146 else:
147 ans = star.repeat(int(r / 2.0))
148 return ans
149
150
151 def human_readable(size, sep=' '):
152 if size <= 0:
153 return f'0{sep}B'
154 i = Math.floor(Math.log(size) / Math.log(1024))
155 size = (size / Math.pow(1024, i)).toFixed(1)
156 if size.endswith('.0'):
157 size = size[:-2]
158 suffix = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'][i]
159 return size + sep + suffix
160
161
162 def document_height():
163 html = document.documentElement
164 return max(document.body.scrollHeight, document.body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight)
165
166
167 def document_width():
168 html = document.documentElement
169 return max(document.body.scrollWidth, document.body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth)
170
171 _data_ns = None
172
173
174 def data_ns(name):
175 nonlocal _data_ns
176 if _data_ns is None:
177 rand = Uint8Array(12)
178 window.crypto.getRandomValues(rand)
179 _data_ns = 'data-' + hexlify(rand) + '-'
180 return _data_ns + name
181
182
183 def get_elem_data(elem, name, defval):
184 ans = elem.getAttribute(data_ns(name))
185 if ans is None:
186 return defval ? None
187 return JSON.parse(ans)
188
189
190 def set_elem_data(elem, name, val):
191 elem.setAttribute(data_ns(name), JSON.stringify(val))
192
193
194 def username_key(username):
195 return ('u' if username else 'n') + username
196
197
198 def html_escape(text):
199 repl = {'&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;'}
200 return String.prototype.replace.call(text, /[&"<>]/g, def (c): return repl[c];)
201
202
203 def uniq(vals):
204 # Remove all duplicates from vals, while preserving order
205 ans = []
206 seen = {}
207 for x in vals:
208 if not seen[x]:
209 seen[x] = True
210 ans.push(x)
211 return ans
212
213
214 def conditional_timeout(elem_id, timeout, func):
215 def ct_impl():
216 elem = document.getElementById(elem_id)
217 if elem:
218 func.call(elem)
219 window.setTimeout(ct_impl, timeout)
220
221
222 def simple_markup(html):
223 html = (html or '').replace(/\uffff/g, '').replace(
224 /<\s*(\/?[a-zA-Z1-6]+)[^>]*>/g, def (match, tag):
225 tag = tag.toLowerCase()
226 is_closing = '/' if tag[0] is '/' else ''
227 if is_closing:
228 tag = tag[1:]
229 if simple_markup.allowed_tags.indexOf(tag) < 0:
230 tag = 'span'
231 return f'\uffff{is_closing}{tag}\uffff'
232 )
233 div = document.createElement('b')
234 div.textContent = html
235 html = div.innerHTML
236 return html.replace(/\uffff(\/?[a-z1-6]+)\uffff/g, '<$1>')
237 simple_markup.allowed_tags = v"'a|b|i|br|hr|h1|h2|h3|h4|h5|h6|div|em|strong|span'.split('|')"
238
239
240 def safe_set_inner_html(elem, html):
241 elem.innerHTML = simple_markup(html)
242 return elem
243
244
245 def sandboxed_html(html, style, sandbox):
246 ans = document.createElement('iframe')
247 ans.setAttribute('sandbox', sandbox or '')
248 ans.setAttribute('seamless', '')
249 ans.style.width = '100%'
250 html = html or ''
251 css = 'html, body { margin: 0; padding: 0; font-family: __FONT__ } p:first-child { margin-top: 0; padding-top: 0; -webkit-margin-before: 0 }'.replace(
252 '__FONT__',
253 get_font_family()
254 )
255 css += style or ''
256 final_html = f'<!DOCTYPE html><html><head><style>{css}</style></head><body>{html}</body></html>'
257 ans.srcdoc = final_html
258 return ans