-
Notifications
You must be signed in to change notification settings - Fork 11
/
action.py
641 lines (498 loc) · 17.8 KB
/
action.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
# coding=utf-8
""""""
from __future__ import absolute_import, division, print_function, \
unicode_literals
import logging
import re
from flask import current_app, g
from flask.signals import appcontext_pushed
from jinja2 import Markup, Template
from six import python_2_unicode_compatible, string_types, text_type
from abilian.core.singleton import UniqueName
from abilian.web import csrf
from abilian.web.util import url_for
log = logging.getLogger(__name__)
__all__ = (
"Action",
"ButtonAction",
"FAIcon",
"ModalActionMixin",
"Endpoint",
"actions",
)
class Status(UniqueName):
"""Action UI status names."""
#: default action status: show in UID, usable, not marked "current"
ENABLED = Status("enabled")
#: action is "active" or "current". For example the current navigation item.
ACTIVE = Status("active")
#: action should be shown in a disabled state
DISABLED = Status("disabled")
def getset(f):
"""Shortcut for a custom getter/ standard setter.
Usage::
@getset
def my_property(self, value=None):
if value is None:
return getter_value
set_value(value)
Default value for `value` should be any marker that helps distinguish
between getter or setter mode. If None is not appropriate a good approach is
to use a unique object instance::
MARK = object()
# test like this
if value is MARK:
# getter mode
"""
return property(f, f)
@python_2_unicode_compatible
class Icon(object):
"""Base abstract class for icons."""
def __html__(self):
raise NotImplementedError
def __str__(self):
return self.__html__()
class NamedIconBase(Icon):
"""Renders markup for named icons set."""
template = None
def __init__(self, name=""):
self.name = name
def __html__(self):
return self.template.render(name=self.name)
class Glyphicon(NamedIconBase):
"""Renders markup for bootstrap's glyphicons."""
template = Template('<i class="glyphicon glyphicon-{{ name }}"></i>')
class FAIcon(NamedIconBase):
"""Renders markup for FontAwesome icons."""
template = Template('<i class="fa fa-{{ name }}"></i>')
class FAIconStacked(NamedIconBase):
"""Stacked FA icons."""
template = Template(
'<span class="fa-stack {%- if stack_class %} {{ stack_class }}'
'{%- endif %}">\n'
' <i class="fa fa-{{ name }}"></i>\n'
' <i class="fa fa-{{ second }}"></i>\n'
"</span>"
)
def __init__(self, name, second, stack=""):
"""
@param name: first icon name, support additional css classes.
@param second: second icon. Can be 'ban fa-stack-2x text-danger' for
example.
@param stack: additional class on top-level element, i.e 'fa-lg'.
"""
if "fa-stack-" not in name:
name += " fa-stack-1x"
if "fa-stack-" not in second:
second += " fa-stack-1x"
super(FAIconStacked, self).__init__(name)
self.second = second
self.stack = stack
def __html__(self):
return self.template.render(
name=self.name, second=self.second, stack_class=self.stack
)
class DynamicIcon(Icon):
template = Template(
'<img {%- if css %} class="{{ css }}"{% endif %} '
'src="{{ url }}" '
'width="{{ width }}" height="{{ height }}" />'
)
def __init__(
self,
endpoint=None,
width=12,
height=12,
css="",
size=None,
url_args=None,
**fixed_url_args
):
self.endpoint = endpoint
self.css = css
self.fixed_url_args = dict()
self.fixed_url_args.update(fixed_url_args)
self.url_args_callback = url_args
if size is not None:
width = height = size
self.width = width
self.height = height
def get_url_args(self):
kw = dict()
kw.update(self.fixed_url_args)
return kw
def __html__(self):
endpoint = self.endpoint
if callable(endpoint):
endpoint = endpoint()
url_args = self.get_url_args()
if self.url_args_callback is not None:
url_args = self.url_args_callback(self, url_args)
return self.template.render(
url=url_for(endpoint, **url_args),
width=self.width,
height=self.height,
css=self.css,
)
class StaticIcon(DynamicIcon):
"""Renders markup for icon located in static folder served by `endpoint`.
Default endpoint is application static folder.
"""
def __init__(
self, filename, endpoint="static", width=12, height=12, css="", size=None
):
DynamicIcon.__init__(
self, endpoint, width, height, css, size, filename=filename
)
@python_2_unicode_compatible
class Endpoint(object):
# FIXME: *args doesn't seem to be relevant.
def __init__(self, name, *args, **kwargs):
self.name = name
self.args = args
self.kwargs = kwargs
def get_kwargs(self):
"""Hook for subclasses.
The key and values in the returned dictionnary can be safely
changed without side effects on self.kwargs (provided you don't
alter mutable values, like calling list.pop()).
"""
return self.kwargs.copy()
def __str__(self):
return text_type(url_for(self.name, **self.get_kwargs()))
def __repr__(self):
return "{cls}({name!r}, *{args!r}, **{kwargs!r})".format(
cls=self.__class__.__name__,
name=self.name,
args=self.args,
kwargs=self.kwargs,
)
class Action(object):
"""Action interface."""
Endpoint = Endpoint
category = None
name = None
title = None
description = None
icon = None
_url = None
CSS_CLASS = "action action-{category} action-{category}-{name}"
#: A :class:`Endpoint` instance, a string for a simple endpoint, a tuple
#: ``(endpoint_name, kwargs)`` or a callable which accept a : context dict
#: and returns one of those a valid values.
endpoint = None
#: A boolean (or something that can be converted to boolean), or a callable
#: which accepts a context dict as parameter. See :meth:`available`.
condition = None
template_string = (
'<a class="{{ action.css_class }}" href="{{ url }}">'
"{%- if action.icon %}{{ action.icon }} {% endif %}"
"{{ action.title }}"
"</a>"
)
def __init__(
self,
category,
name,
title=None,
description=None,
icon=None,
url=None,
endpoint=None,
condition=None,
status=None,
template=None,
template_string=None,
button=None,
css=None,
):
"""
:param button: if not `None`, a valid `btn` class (i.e `default`,
`primary`...)
:param css: additional css class string
:param template: optional: a template file name or a list of filenames.
:param template_string: template_string to use. Defaults to
`Action.template_string`
"""
self.category = category
self.name = name
if button is not None:
self.CSS_CLASS += " btn btn-{}".format(button)
if css is not None:
self.CSS_CLASS = self.CSS_CLASS + " " + css
self._build_css_class()
self._title = title
self._description = description
if isinstance(icon, string_types):
icon = Glyphicon(icon)
self._icon = icon
self._url = url
self._status = Status(status) if status is not None else ENABLED
self._endpoint = endpoint
if not callable(endpoint) and not isinstance(endpoint, Endpoint):
# property getter will make it and Endpoint instance
self.endpoint = self.endpoint
self.condition = condition
self._enabled = True
self.template = template
if template_string:
self.template_string = template_string
#: ui status. A :class:`Status` instance
@getset
def status(self, value=None):
status = self._status
if value is not None:
self._status = status = Status(value)
return status
#: Boolean. Disabled actions are unconditionnaly skipped.
@getset
def enabled(self, value=None):
enabled = self._enabled
if value is not None:
assert isinstance(value, bool)
self._enabled = enabled = value
return enabled
def _get_and_call(self, attr):
attr = "_" + attr
value = getattr(self, attr)
if callable(value):
value = value(actions.context)
return value
@property
def title(self):
return self._get_and_call("title")
@title.setter
def title(self, title):
self._title = title
def _build_css_class(self):
css_cat = self.CSS_CLASS.format(
action=self, category=self.category, name=self.name
)
css_cat = re.sub(r"[^ _a-zA-Z0-9-]", "-", css_cat)
self.css_class = css_cat
@property
def description(self):
return self._get_and_call("description")
@description.setter
def description(self, description):
self._description = description
@property
def icon(self):
return self._get_and_call("icon")
@icon.setter
def icon(self, icon):
self._icon = icon
@property
def endpoint(self):
endpoint = self._get_and_call("endpoint")
if endpoint is None:
return
if not isinstance(endpoint, Endpoint):
if isinstance(endpoint, string_types):
endpoint = self.Endpoint(endpoint)
elif isinstance(endpoint, (tuple, list)):
assert len(endpoint) == 2
endpoint, kwargs = endpoint
assert isinstance(endpoint, string_types)
assert isinstance(kwargs, dict)
endpoint = self.Endpoint(endpoint, **kwargs)
else:
raise ValueError(
'Invalid endpoint specifier: "{}"'.format(repr(endpoint))
)
return endpoint
@endpoint.setter
def endpoint(self, endpoint):
self._endpoint = endpoint
def available(self, context):
"""Determine if this actions is available in this `context`.
:param context: a dict whose content is left to application needs; if
:attr:`.condition` is a callable it receives `context`
in parameter.
"""
if not self._enabled:
return False
try:
return self.pre_condition(context) and self._check_condition(context)
except BaseException:
return False
def pre_condition(self, context):
"""Called by :meth:`.available` before checking condition.
Subclasses may override it to ease creating actions with
repetitive check (for example: actions that apply on a given
content type only).
"""
return True
def _check_condition(self, context):
if self.condition is None:
return True
if callable(self.condition):
return self.condition(context)
else:
return bool(self.condition)
def render(self, **kwargs):
if not self.template:
self.template = Template(self.template_string)
template = self.template
if not isinstance(template, Template):
template = current_app.jinja_env.get_or_select_template(template)
params = self.get_render_args(**kwargs)
return Markup(template.render(params))
def get_render_args(self, **kwargs):
params = dict(action=self)
params.update(actions.context)
params.update(kwargs)
params["csrf"] = csrf
params["url"] = self.url(params)
return params
def url(self, context=None):
if callable(self._url):
return self._url(context)
endpoint = self.endpoint
if endpoint:
return text_type(endpoint)
return self._url
class ModalActionMixin(object):
template_string = (
'<a class="{{ action.css_class }}" href="{{ url }}" data-toggle="modal">'
"{%- if action.icon %}{{ action.icon}} {% endif %}"
"{{ action.title }}"
"</a>"
)
class ButtonAction(Action):
template_string = (
'<button type="submit" '
'class="btn btn-{{ action.btn_class }} {{ action.css_class}}" '
'name="{{ action.submit_name }}" '
'value="{{ action.name }}">'
"{%- if action.icon %}{{ action.icon }} {% endif %}"
"{{ action.title }}</button>"
)
btn_class = "default"
def __init__(
self,
category,
name,
submit_name="__action",
btn_class="default",
*args,
**kwargs
):
Action.__init__(self, category, name, *args, **kwargs)
self.submit_name = submit_name
self.btn_class = btn_class
class ActionGroup(Action):
"""A group of single actions."""
template_string = (
'<div class="btn-group" role="group" aria-label="{{ action.name}}">'
"{%- for entry in action_items %}"
"{{ entry.render() }}"
"{%- endfor %}"
"</div>"
)
def __init__(self, category, name, items=(), *args, **kwargs):
super(ActionGroup, self).__init__(category, name, *args, **kwargs)
self.items = list(items)
def get_render_args(self, **kwargs):
params = super(ActionGroup, self).get_render_args(**kwargs)
params["action_items"] = [a for a in self.items if a.available(params)]
return params
class ActionDropDown(ActionGroup):
"""Renders as a button dropdown."""
template_string = """
<div class="btn-group">
<button type="button" class="{{ action.css_class }} dropdown-toggle"
data-toggle="dropdown" aria-expanded="false">
{%- if action.icon %}{{ action.icon }} {% endif %}
{{ action.title }}
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
{%- for entry in action_items %}
{%- if entry.divider %}<li class="divider"></li>{%- endif %}
<li>{{ entry.render() }}</a>
</li>
{%- endfor %}
</ul>
</div>
"""
class ActionGroupItem(Action):
#: if True, add a divider in dropdowns
divider = False
def __init__(self, category, name, divider=False, *args, **kwargs):
super(ActionGroupItem, self).__init__(category, name, *args, **kwargs)
self.divider = divider
class ActionRegistry(object):
"""The Action registry.
This is a Flask extension which registers :class:`.Action` sets. Actions are
grouped by category and are ordered by registering order.
From your application use the instanciated registry :data:`.actions`.
The registry is available in jinja2 templates as `actions`.
"""
__EXTENSION_NAME = "abilian:actions"
def init_app(self, app):
if self.__EXTENSION_NAME in app.extensions:
log.warning(
"ActionRegistry.init_app: actions already enabled on this application"
)
return
app.extensions[self.__EXTENSION_NAME] = dict(categories=dict())
appcontext_pushed.connect(self._init_context, app)
@app.context_processor
def add_registry_to_jinja_context():
return dict(actions=self)
def installed(self, app=None):
"""Return `True` if the registry has been installed in current
applications."""
if app is None:
app = current_app
return self.__EXTENSION_NAME in app.extensions
def register(self, *actions):
"""Register `actions` in the current application. All `actions` must be
an instance of :class:`.Action` or one of its subclasses.
If `overwrite` is `True`, then it is allowed to overwrite an
existing action with same name and category; else `ValueError`
is raised.
"""
assert self.installed(), "Actions not enabled on this application"
assert all(isinstance(a, Action) for a in actions)
for action in actions:
cat = action.category
reg = self._state["categories"].setdefault(cat, [])
reg.append(action)
def actions(self, context=None):
"""Return a mapping of category => actions list.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`).
"""
assert self.installed(), "Actions not enabled on this application"
result = {}
if context is None:
context = self.context
for cat, actions in self._state["categories"].items():
result[cat] = [a for a in actions if a.available(context)]
return result
def for_category(self, category, context=None):
"""Returns actions list for this category in current application.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`)
"""
assert self.installed(), "Actions not enabled on this application"
actions = self._state["categories"].get(category, [])
if context is None:
context = self.context
return [a for a in actions if a.available(context)]
@property
def _state(self):
return current_app.extensions[self.__EXTENSION_NAME]
def _init_context(self, sender):
g.action_context = {}
@property
def context(self):
"""Return action context (dict type).
Applications can modify it to suit their needs.
"""
return g.action_context
actions = ActionRegistry()