-
Notifications
You must be signed in to change notification settings - Fork 17
/
widgets.py
346 lines (295 loc) · 10.6 KB
/
widgets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import six
from flask import Markup, current_app, render_template
from wtforms.compat import text_type
from wtforms.widgets import RadioInput, Select, html_params
import wtforms
from furl import furl
from .. import b_ as _
__all__ = [
'TinyMce3',
'TinyMce4',
'SubmitInput',
'DateTimeInput',
'CoordinatesInput',
'RadioMatrixInput',
'ImgeeWidget',
'InlineListWidget',
'RadioInput',
'SelectWidget',
'Select2Widget',
]
# This class borrowed from https://github.com/industrydive/wtforms_extended_selectfield
class SelectWidget(Select):
"""
Add support of choices with ``optgroup`` to the ``Select`` widget.
"""
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
if self.multiple:
kwargs['multiple'] = True
html = ['<select %s>' % html_params(name=field.name, **kwargs)]
for item1, item2 in field.choices:
if isinstance(item2, (list, tuple)):
group_label = item1
group_items = item2
html.append('<optgroup %s>' % html_params(label=group_label))
for inner_val, inner_label in group_items:
html.append(
self.render_option(
inner_val,
inner_label,
field.coerce(inner_val) == field.data,
)
)
html.append('</optgroup>')
else:
val = item1
label = item2
html.append(self.render_option(val, label, val == field.data))
html.append('</select>')
return Markup(''.join(html))
class Select2Widget(Select):
"""
Add a select2 class to the rendered select widget
"""
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
kwargs.pop('type', field.type)
if field.multiple:
kwargs['multiple'] = 'multiple'
c = kwargs.pop('class', '') or kwargs.pop('class_', '')
if c:
kwargs['class'] = '%s %s' % ('select2', c)
else:
kwargs['class'] = 'select2'
html = ['<select %s>' % html_params(name=field.name, **kwargs)]
if field.iter_choices():
for val, label, selected in field.iter_choices():
html.append(self.render_option(val, label, selected))
html.append('</select>')
return Markup(''.join(html))
class TinyMce3(wtforms.widgets.TextArea):
"""
Rich text widget with Tiny MCE 3.
"""
input_type = "tinymce3"
def __call__(self, field, **kwargs):
c = kwargs.pop('class', '') or kwargs.pop('class_', '')
if c:
kwargs['class'] = '%s %s' % ('richtext', c)
else:
kwargs['class'] = 'richtext'
return super(TinyMce3, self).__call__(field, **kwargs)
class TinyMce4(wtforms.widgets.TextArea):
"""
Rich text widget with Tiny MCE 4.
"""
input_type = "tinymce4"
def __call__(self, field, **kwargs):
c = kwargs.pop('class', '') or kwargs.pop('class_', '')
if c:
kwargs['class'] = '%s %s' % ('richtext', c)
else:
kwargs['class'] = 'richtext'
return super(TinyMce4, self).__call__(field, **kwargs)
class SubmitInput(wtforms.widgets.SubmitInput):
"""
Submit input with pre-defined classes.
"""
def __init__(self, *args, **kwargs):
self.css_class = kwargs.pop('class', '') or kwargs.pop('class_', '')
super(SubmitInput, self).__init__(*args, **kwargs)
def __call__(self, field, **kwargs):
c = kwargs.pop('class', '') or kwargs.pop('class_', '')
kwargs['class'] = '%s %s' % (self.css_class, c)
return super(SubmitInput, self).__call__(field, **kwargs)
class DateTimeInput(wtforms.widgets.Input):
"""
Render date and time inputs.
"""
input_type = 'datetime'
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
field_id = kwargs.pop('id')
kwargs.pop('type', None)
value = kwargs.pop('value', None)
if value is None:
value = field._value()
if not value:
value = ' '
class_ = kwargs.pop('class', kwargs.pop('class_', ''))
date_value, time_value = value.split(' ', 1)
return Markup(
'<input type="date" class="datetime-date %s" %s /> <input type="time" class="datetime-time %s" %s /> %s'
% (
class_,
wtforms.widgets.html_params(
name=field.name,
id=field_id + '-date',
value=date_value,
placeholder="yyy-mm-dd",
**kwargs
),
class_,
wtforms.widgets.html_params(
name=field.name,
id=field_id + '-time',
value=time_value,
placeholder="--:--",
**kwargs
),
field.tzname,
)
)
class CoordinatesInput(wtforms.widgets.core.Input):
"""
Render latitude and longitude coordinates
"""
input_type = 'text'
def __call__(self, field, **kwargs):
id_ = kwargs.pop('id', field.id)
kwargs.setdefault('type', self.input_type)
kwargs.setdefault('size', 10) # 9 digits precision and +/- sign
kwargs.pop(
'placeholder', None
) # Discard placeholder, use custom values for each input below
value = kwargs.pop('value', None)
if not value:
value = field._value()
if not value:
value = ['', '']
elif isinstance(value, six.string_types):
value = value.split(',', 1)
if len(value) < 2:
value.append('')
return Markup(
'<input %s> <input %s>'
% (
self.html_params(
id=id_ + '_latitude',
name=field.name,
placeholder=_("Latitude"),
value=value[0],
**kwargs
),
self.html_params(
id=id_ + '_longitude',
name=field.name,
placeholder=_("Longitude"),
value=value[1],
**kwargs
),
)
)
class RadioMatrixInput(object):
"""
Render a table with a radio matrix
"""
def __call__(self, field, **kwargs):
rendered = []
rendered.append('<table class="%s">' % kwargs.pop('table_class', 'table'))
rendered.append('<thead>')
rendered.append('<tr>')
rendered.append('<th>%s</th>' % field.label)
for value, label in field.choices:
rendered.append('<th>%s</th>' % label)
rendered.append('</th>')
rendered.append('</thead>')
rendered.append('<tbody>')
for name, title in field.fields:
rendered.append('<tr>')
rendered.append('<td>%s</td>' % title)
selected = field.data.get(name)
for value, label in field.choices:
params = {'type': 'radio', 'name': name, 'value': value}
if text_type(selected) == text_type(value):
params['checked'] = True
rendered.append(
'<td><input %s/></td>' % wtforms.widgets.html_params(**params)
)
rendered.append('</tr>')
rendered.append('</tbody>')
rendered.append('</table>')
return Markup('\n'.join(rendered))
class InlineListWidget(object):
"""
Renders a list of fields as buttons.
This is used for fields which encapsulate many inner fields as subfields.
The widget will try to iterate the field to get access to the subfields and
call them to render them.
If `prefix_label` is set, the subfield's label is printed before the field,
otherwise afterwards. The latter is useful for iterating radios or
checkboxes.
"""
def __init__(self, html_tag='div', class_='', class_prefix=''):
self.html_tag = html_tag
self.class_ = ''
self.class_prefix = class_prefix
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
kwargs['class_'] = (
kwargs.pop('class_', kwargs.pop('class', '')).strip() + ' ' + self.class_
).strip()
html = ['<%s %s>' % (self.html_tag, wtforms.widgets.html_params(**kwargs))]
for subfield in field:
html.append(
'<label for="%s" class="%s%s">%s %s</label>'
% (
subfield.id,
self.class_prefix,
subfield.data,
subfield(),
subfield.label.text,
)
)
html.append('</%s>' % self.html_tag)
return Markup('\n'.join(html))
class ImgeeWidget(wtforms.widgets.Input):
input_type = 'hidden'
def __call__(self, field, **kwargs):
id_ = kwargs.pop('id', field.id)
kwargs.setdefault('type', self.input_type)
imgee_host = current_app.config.get('IMGEE_HOST')
if not imgee_host:
raise ValueError("No imgee server specified in config variable IMGEE_HOST")
upload_url = f'{imgee_host}/{field.profile}/popup'
value = kwargs.pop('value', None)
if not value:
value = field._value()
if not value:
value = ''
elif isinstance(value, furl):
value = furl.url
iframe_html = Markup(
'<iframe %s class="imgee-upload"></iframe>'
% (
self.html_params(
id='iframe_' + id_ + '_upload',
input_id=id_,
src=upload_url,
),
)
)
field_html = Markup(
'<img %s> <input %s>'
% (
self.html_params(id='img_' + id_, src=value, width='200', **kwargs),
self.html_params(
id=id_,
name=field.name,
placeholder=_("Image URL"),
value=value,
**kwargs
),
)
)
return Markup(
render_template(
'baseframe/mui/imgeefield.html.jinja2',
field=field,
iframe_html=iframe_html,
field_html=field_html,
)
)