/
base.py
527 lines (426 loc) · 13.7 KB
/
base.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
"""Base classes for actions.
Version Added:
6.0
"""
from __future__ import annotations
from typing import Any, List, Mapping, Optional, TYPE_CHECKING, cast
from django.http import HttpRequest
from django.template import Context
from django.template.loader import render_to_string
from django.utils.safestring import SafeText, mark_safe
from reviewboard.site.urlresolvers import local_site_reverse
if TYPE_CHECKING:
# This is available only in django-stubs.
from django.utils.functional import _StrOrPromise
class AttachmentPoint:
"""Attachment points for actions.
Version Added:
6.0
"""
#: Attachment for actions which do not want to render in the UI.
#:
#: This can be used for actions which want to be JavaScript-only, and may
#: be used in the future for things like keyboard shortcuts or a command-K
#: bar.
NON_UI = 'non-ui'
#: Attachment for actions in the page header.
HEADER = 'header'
#: Attachment for actions on the left side of the review request header.
REVIEW_REQUEST_LEFT = 'review-request-left'
#: Attachment for actions on the right side of the review request header.
REVIEW_REQUEST = 'review-request'
#: Attachment for actions in the unified draft banner.
UNIFIED_BANNER = 'unified-banner'
class BaseAction:
"""Base class for actions.
Version Added:
6.0
"""
#: The internal ID of the action.
#:
#: This must be unique.
#:
#: Type:
#: str
action_id: Optional[str] = None
#: A list of URLs to apply to.
#:
#: If this is ``None``, the action will be loaded on all pages. Otherwise,
#: it will be limited to the URLs listed here.
#:
#: Type:
#: list of str
apply_to: Optional[List[str]] = None
#: The attachment point for the action.
#:
#: Type:
#: str
attachment: str = AttachmentPoint.REVIEW_REQUEST
#: A class name to use for an icon.
#:
#: If specified, this should be the entire class to apply to a <span>
#: element to display an icon. For example, 'fa fa-rss'.
#:
#: Type:
#: str
icon_class: Optional[str] = None
#: The class to instantiate for the JavaScript model.
#:
#: Type:
#: str
js_model_class: str = 'RB.Actions.Action'
#: The name of the template to use for rendering action JavaScript.
#:
#: Type
#: str
js_template_name: str = 'actions/action.js'
#: The class to instantiate for the JavaScript view.
#:
#: Type:
#: str
js_view_class: str = 'RB.Actions.ActionView'
#: The user-visible label.
#:
#: Type:
#: str
label: Optional[_StrOrPromise] = None
#: The ID of the parent menu action, if available.
#:
#: Type:
#: str
parent_id: Optional[str] = None
#: The name of the template to use when rendering.
#:
#: Type:
#: str
template_name: str = 'actions/action.html'
#: The URL that this action links to.
#:
#: Type:
#: str
url: str = '#'
#: A URL name to resolve.
#:
#: If this is not None, it will take precedence over :py:attr:`url`.
#:
#: Type:
#: str
url_name: Optional[str] = None
#: Whether this action is visible.
#:
#: Type:
#: bool
visible: bool = True
######################
# Instance variables #
######################
#: The list of child actions, if this is a menu.
#:
#: Type:
#: list of BaseAction
child_actions: List[BaseAction]
#: The parent of this action, if this is a menu item.
#:
#: Type:
#: BaseMenuAction
parent_action: Optional[BaseMenuAction]
#: Whether this action has been hidden by an extension.
#:
#: Type:
#: boolean
_hidden_by_extension: Optional[bool] = None
def __init__(self) -> None:
"""Initialize the action."""
self.parent_action = None
self.child_actions = []
@property
def depth(self) -> int:
"""The depth of the action.
Type:
int
"""
if self.parent_action is None:
return 0
else:
return self.parent_action.depth + 1
def should_render(
self,
*,
context: Context,
) -> bool:
"""Return whether this action should render.
This differs from :py:attr:`visible` in that non-visible actions still
render but are hidden by CSS, whereas if this returns ``False`` the
action will not be included in the DOM at all.
Args:
context (django.template.Context):
The current rendering context.
Returns:
bool:
``True`` if the action should render.
"""
request = context['request']
if (self.parent_action and not
self.parent_action.should_render(context=context)):
return False
if (self.apply_to and not
(request.resolver_match and
request.resolver_match.url_name in self.apply_to)):
return False
if self._hidden_by_extension is None:
from reviewboard.extensions.hooks.actions import HideActionHook
for hook in HideActionHook.hooks:
if self.action_id in hook.hidden_action_ids:
self._hidden_by_extension = True
break
else:
self._hidden_by_extension = False
if self._hidden_by_extension:
return False
return True
def get_dom_element_id(self) -> str:
"""Return the ID used for the DOM element for this action.
Returns:
str:
The ID used for the element.
"""
return 'action-%s' % self.action_id
def get_js_model_data(
self,
*,
context: Context,
) -> dict:
"""Return data to be passed to the JavaScript model.
Args:
context (django.template.Context):
The current rendering context.
Returns:
dict:
A dictionary of attributes to pass to the model instance.
"""
return {
'actionId': self.action_id,
'visible': self.visible,
}
def get_js_view_data(
self,
*,
context: Context,
) -> dict:
"""Return data to be passed to the JavaScript view.
Args:
context (django.template.Context):
The current rendering context.
Returns:
dict:
A dictionary of options to pass to the view instance.
"""
return {}
def get_label(
self,
*,
context: Context,
) -> _StrOrPromise:
"""Return the label for the action.
Args:
context (django.template.Context):
The current rendering context.
Returns:
str:
The label to use for the action.
"""
assert self.label is not None
return self.label
def get_url(
self,
*,
context: Context,
) -> str:
"""Return the URL for the action.
Args:
context (django.template.Context):
The current rendering context.
Returns:
str:
The URL to use for the action.
"""
assert self.url_name or self.url
if self.url_name:
return local_site_reverse(self.url_name,
request=context.get('request'))
else:
return self.url
def get_visible(
self,
*,
context: Context,
) -> bool:
"""Return whether the action should start visible.
Args:
context (django.template.Context):
The current rendering context.
Returns:
bool:
``True`` if the action should start visible. ``False``, otherwise.
"""
return self.visible
def get_extra_context(
self,
*,
request: HttpRequest,
context: Context,
) -> dict:
"""Return extra template context for the action.
Subclasses can override this to provide additional context needed by
the template for the action. By default, this returns an empty
dictionary.
Args:
request (django.http.HttpRequest):
The HTTP request from the client.
context (django.template.Context):
The current rendering context.
Returns:
dict:
Extra context to use when rendering the action's template.
"""
return {
'has_parent': self.parent_id is not None,
'id': self.action_id,
'label': self.get_label(context=context),
'url': self.get_url(context=context),
'visible': self.get_visible(context=context),
}
def render(
self,
*,
request: HttpRequest,
context: Context,
) -> SafeText:
"""Render the action.
Args:
request (django.http.HttpRequest):
The HTTP request from the client.
context (django.template.Context):
The current rendering context.
Returns:
django.utils.safestring.SafeText:
The rendered action HTML.
"""
if self.should_render(context=context):
context.push()
try:
context['action'] = self
context.update(self.get_extra_context(request=request,
context=context))
return render_to_string(
template_name=self.template_name,
context=cast(Mapping[str, Any], context.flatten()),
request=request)
finally:
context.pop()
else:
return mark_safe('')
def render_js(
self,
*,
request: HttpRequest,
context: Context,
) -> SafeText:
"""Render the action's JavaScript.
Args:
request (django.http.HttpRequest):
The HTTP request from the client.
context (django.template.Context):
The current rendering context.
Returns:
django.utils.safestring.SafeText:
The rendered action JavaScript.
"""
if self.js_template_name and self.should_render(context=context):
context.push()
try:
context['action'] = self
return render_to_string(
template_name=self.js_template_name,
context=cast(Mapping[str, Any], context.flatten()),
request=request)
finally:
context.pop()
else:
return mark_safe('')
class BaseMenuAction(BaseAction):
"""Base class for menu actions.
Version Added:
6.0
"""
template_name = 'actions/menu_action.html'
js_model_class = 'RB.Actions.MenuAction'
js_view_class = 'RB.Actions.MenuActionView'
#: An ordered list of child menu IDs.
#:
#: This can be used to specify a specific order for children to appear in.
#: The special string '--' can be used to add separators. Any children that
#: are registered with this menu as their parent but do not appear in this
#: list will be added at the end of the menu.
children: List[str] = []
def get_extra_context(
self,
*,
request: HttpRequest,
context: Context,
) -> dict:
"""Return extra template context for the action.
Subclasses can override this to provide additional context needed by
the template for the action. By default, this returns an empty
dictionary.
Args:
request (django.http.HttpRequest):
The HTTP request from the client.
context (django.template.Context):
The current rendering context.
Returns:
dict:
Extra context to use when rendering the action's template.
"""
from reviewboard.actions import actions_registry
extra_context = super().get_extra_context(request=request,
context=context)
extra_context['children'] = ([
child
for child in actions_registry.get_children(self.action_id)
if child.should_render(context=context)
])
return extra_context
def get_js_model_data(
self,
*,
context: Context,
) -> dict:
"""Return data to be passed to the JavaScript model.
Args:
context (django.template.Context):
The current rendering context.
Returns:
dict:
A dictionary of attributes to pass to the model instance.
"""
from reviewboard.actions import actions_registry
rendered_child_ids = [
child.action_id
for child in actions_registry.get_children(self.action_id)
if child.should_render(context=context)
]
children = []
# Add in any children with explicit ordering first.
for child_id in self.children:
if child_id == '--':
children.append(child_id)
elif child_id in rendered_child_ids:
children.append(child_id)
rendered_child_ids.remove(child_id)
# Now add any other actions that weren't in self.children.
for child_id in rendered_child_ids:
children.append(child_id)
data = super().get_js_model_data(context=context)
data['children'] = children
return data