-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathblocks.py
More file actions
644 lines (524 loc) · 19 KB
/
blocks.py
File metadata and controls
644 lines (524 loc) · 19 KB
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
642
643
644
import re
from django import forms
from django.forms.utils import ErrorList
from wagtail import blocks
from wagtail.blocks import StructBlockValidationError
from wagtail.embeds.blocks import EmbedBlock
from wagtail.images.blocks import ImageChooserBlock
from wagtail.rich_text import RichText
import bleach
from common.choices import BACKGROUND_COLOR_CHOICES
from common.models.charts import (
BubbleMapChartOptionsSchema,
HexbinMapChartOptionsSchema,
)
from common.models.helpers import get_categories, get_states, get_tags
from common.search import get_searchable_content_for_fields
from common.templatetags.render_as_template import render_as_template
from common.utils import unescape
from common.utils.chart_pregenerator.types import ChartType
from common.utils.charts import ChartValue
from common.validators import validate_template
from incident.utils import charts
class RichTextTemplateBlock(blocks.RichTextBlock):
def __init__(self, editor=None, **kwargs):
if not editor:
editor = "num-incident-full-features"
super().__init__(
editor=editor,
**kwargs,
)
def clean(self, value):
cleaned_value = super(RichTextTemplateBlock, self).clean(value)
# cleaned_value is a wagtail.rich_text.RichText instance.
# RichText.source is the raw HTML value.
validate_template(cleaned_value.source)
return RichText(unescape(cleaned_value.source))
def render_basic(self, value, context=None):
return render_as_template(value)
class Heading1(blocks.StructBlock):
content = blocks.CharBlock()
class Meta:
template = "common/blocks/heading_1.html"
icon = "title"
label = "Heading 1"
class Heading2(blocks.StructBlock):
content = blocks.CharBlock()
class Meta:
template = "common/blocks/heading_2.html"
icon = "title"
label = "Heading 2"
class Heading3(blocks.StructBlock):
content = blocks.CharBlock()
class Meta:
template = "common/blocks/heading_3.html"
icon = "title"
label = "Heading 3"
ALIGNMENT_CHOICES = (
("left", "Left"),
("right", "Right"),
("full-width", "Full Width"),
)
class AlignedCaptionedImageBlock(blocks.StructBlock):
image = ImageChooserBlock()
caption = blocks.RichTextBlock(
required=False,
help_text="Image description displayed below the image. Organization/Photographer can be set via the image attribution.",
)
alignment = blocks.ChoiceBlock(choices=ALIGNMENT_CHOICES)
content_warning = blocks.ListBlock(
blocks.CharBlock(
label="Warning text",
help_text="Warning text shown on the button above blurred media",
default="This image may be disturbing. Tap or click to reveal.",
required=True,
),
min_num=0,
max_num=1,
default=[],
label="Add content warning",
)
def get_searchable_content(self, value):
return get_searchable_content_for_fields(value, self.child_blocks, ["caption"])
def get_context(self, value, **kwargs):
context = super(AlignedCaptionedImageBlock, self).get_context(value, **kwargs)
if value["content_warning"] and isinstance(
value["content_warning"], blocks.list_block.ListValue
):
value["content_warning"] = value["content_warning"][0]
return context
class Meta:
template = "common/blocks/aligned_captioned_image.html"
icon = "image"
label = "Image"
class AlignedCaptionedEmbedBlock(blocks.StructBlock):
video = EmbedBlock()
caption = blocks.RichTextBlock(
required=False, help_text="Video description displayed below the video."
)
attribution = blocks.CharBlock(
max_length=255, required=False, help_text="Organization / Director."
)
alignment = blocks.ChoiceBlock(choices=ALIGNMENT_CHOICES)
def get_searchable_content(self, value):
return get_searchable_content_for_fields(
value,
self.child_blocks,
["caption", "attribution"],
)
class Meta:
template = "common/blocks/aligned_captioned_embed.html"
icon = "media"
label = "Video"
class BlueskyEmbedBlock(blocks.StructBlock):
bluesky_post = EmbedBlock(
help_text=(
"Link to a Bluesky post, "
"copied by using the Share button and Copy link to post."
)
)
class Meta:
icon = "pick"
label = "Bluesky embed"
template = "common/blocks/bluesky_embed.html"
class InstagramEmbedBlock(blocks.StructBlock):
instagram_post = EmbedBlock(
help_text=(
"Link to an Instagram post, copied by using the … button and Copy Link."
)
)
class Meta:
icon = "pick"
label = "Instagram"
template = "common/blocks/instagram_embed.html"
class TweetEmbedBlock(blocks.StructBlock):
tweet = EmbedBlock()
class Meta:
template = "common/blocks/tweet_embed.html"
icon = "pick"
label = "Tweet"
def clean(self, value):
errors = {}
twitter_url = r"^(http|https):\/\/(twitter|x).com"
tweet = value.get("tweet")
if tweet:
valid = re.match(twitter_url, tweet.url)
if not valid:
errors["tweet"] = ErrorList(["Please enter a valid Twitter URL."])
if errors:
raise StructBlockValidationError(block_errors=errors)
return super().clean(value)
def get_searchable_content(self, value):
tweet_content = value.get("tweet", None)
if tweet_content and tweet_content.html:
return [bleach.clean(tweet_content.html, strip=True, tags={})]
else:
return []
class AsideBlock(blocks.StructBlock):
text = blocks.RichTextBlock()
class Meta:
template = "common/blocks/aside_block.html"
icon = "doc-full-inverse"
label = "Aside"
class StyledTextBlock(blocks.StructBlock):
TEXT_ALIGN_CHOICES = (
("left", "Left"),
("center", "Center"),
("right", "Right"),
)
FONT_SIZE_CHOICES = (
("small", "Small"),
("normal", "Normal"),
("large", "Large"),
("jumbo", "Jumbo"),
)
FONT_FAMILY_CHOICES = (
("sans-serif", "Sans Serif"),
("serif", "Serif"),
)
text = blocks.RichTextBlock()
# These fields are assumed to be deprecated and are left for legacy purposes
# The template does not use the values of these fields
background_color = blocks.ChoiceBlock(
choices=BACKGROUND_COLOR_CHOICES, default="white"
)
text_align = blocks.ChoiceBlock(choices=TEXT_ALIGN_CHOICES, default="left")
font_size = blocks.ChoiceBlock(choices=FONT_SIZE_CHOICES, default="normal")
font_family = blocks.ChoiceBlock(choices=FONT_FAMILY_CHOICES, default="sans-serif")
class Meta:
template = "common/blocks/styled_text.html"
icon = "doc-full"
label = "Styled Text Block"
class StyledTextTemplateBlock(StyledTextBlock):
text = RichTextTemplateBlock(editor="num-incident-full-features")
def get_context(self, *args, **kwargs):
context = super(StyledTextTemplateBlock, self).get_context(*args, **kwargs)
context["render_as_template"] = True
return context
class LogoListBlock(blocks.ListBlock):
def __init__(self, **kwargs):
super(LogoListBlock, self).__init__(
blocks.StructBlock(
[
("logo", ImageChooserBlock(required=True)),
("url", blocks.URLBlock(required=False)),
]
),
template="common/blocks/logo_list_block.html",
**kwargs,
)
class Meta:
icon = "list-ul"
class StatTableBlock(blocks.ListBlock):
def __init__(self, **kwargs):
super(StatTableBlock, self).__init__(
blocks.StructBlock(
[
("header", blocks.TextBlock(required=True)),
(
"value",
blocks.CharBlock(required=True, validators=[validate_template]),
),
]
),
template="common/blocks/stat_table_block.html",
**kwargs,
)
class Meta:
icon = "list-ul"
class TabbedBlock(blocks.ListBlock):
def __init__(self, **kwargs):
super(TabbedBlock, self).__init__(
blocks.StructBlock(
[
("header", blocks.TextBlock(required=True)),
(
"value",
blocks.StreamBlock(
[
("heading_2", Heading2()),
("raw_html", blocks.RawHTMLBlock()),
("rich_text", blocks.RichTextBlock()),
("tweet", TweetEmbedBlock()),
("instagram", InstagramEmbedBlock()),
("bluesky", BlueskyEmbedBlock()),
]
),
),
]
),
template="common/blocks/tabbed_block.html",
**kwargs,
)
class Meta:
icon = "list-ul"
class ButtonBlock(blocks.StructBlock):
text = blocks.TextBlock(required=True)
url = blocks.URLBlock(required=True)
class Meta:
template = "common/blocks/button.html"
class RichTextBlockQuoteBlock(blocks.StructBlock):
text = blocks.RichTextBlock()
source_text = blocks.RichTextBlock(required=False)
source_url = blocks.URLBlock(
required=False, help_text="Source text will link to this url."
)
class Meta:
template = "common/blocks/blockquote.html"
icon = "openquote"
class PullQuoteBlock(blocks.StructBlock):
text = blocks.TextBlock()
class Meta:
template = "common/blocks/pull_quote_block.html"
icon = "openquote"
class EmailSignupBlock(blocks.StructBlock):
text = blocks.CharBlock(
label="Call to action text",
help_text="Defaults to sitewide setting",
required=False,
)
success_text = blocks.CharBlock(
label="Success text",
help_text="To be displayed after a successful signup. Defaults to sitewide setting",
required=False,
)
class Meta:
template = "common/blocks/emails_signup.html"
icon = "form"
label = "Newsletter Signup"
class AbstractInfoTableCTABlock(blocks.StructBlock):
cta_label = blocks.CharBlock(
help_text='Label to be displayed for row link, e.g. "Read the bio", "Contact us", "Visit the page", etc.',
)
class Meta:
abstract = True
class InfoTableBlockPage(AbstractInfoTableCTABlock):
table_data = blocks.ListBlock(
blocks.StructBlock(
[
("page", blocks.PageChooserBlock()),
(
"title",
blocks.CharBlock(
help_text="Optional: defaults to page title",
required=False,
),
),
("description", blocks.CharBlock()),
],
icon="list-ul",
label="Table row",
)
)
class Meta:
template = "common/blocks/info_table/_page.html"
icon = "doc-full"
class InfoTableBlockEmail(AbstractInfoTableCTABlock):
table_data = blocks.ListBlock(
blocks.StructBlock(
[
("title", blocks.CharBlock()),
("email", blocks.EmailBlock()),
],
icon="list-ul",
label="Table row",
)
)
class Meta:
template = "common/blocks/info_table/_email.html"
icon = "mail"
class InfoTableBlockURL(AbstractInfoTableCTABlock):
table_data = blocks.ListBlock(
blocks.StructBlock(
[
(
"image",
ImageChooserBlock(
required=False,
),
),
("title", blocks.CharBlock()),
("url", blocks.URLBlock()),
],
icon="list-ul",
label="Table row",
)
)
class Meta:
template = "common/blocks/info_table/_url.html"
icon = "site"
class InfoTableBlockText(blocks.StructBlock):
table_data = blocks.ListBlock(
blocks.StructBlock(
[
("title", blocks.CharBlock()),
("description", blocks.CharBlock()),
],
icon="list-ul",
label="Table row",
)
)
class Meta:
template = "common/blocks/info_table/_text.html"
icon = "pilcrow"
class InfoTableBlock(blocks.StructBlock):
heading = blocks.CharBlock(
help_text="Heading of the info table",
)
table = blocks.StreamBlock(
[
("page_links", InfoTableBlockPage()),
("email_addresses", InfoTableBlockEmail()),
("external_links", InfoTableBlockURL()),
("plain_text", InfoTableBlockText()),
],
max_num=1,
icon="list-ul",
label="Table type",
)
class Meta:
template = "common/blocks/info_table.html"
icon = "list-ul"
label = "Info table"
class SimpleIncidentSet(blocks.StructBlock):
categories = blocks.MultipleChoiceBlock(
label="Filter by Category",
required=False,
widget=forms.CheckboxSelectMultiple,
choices=get_categories,
help_text="If selected, incidents belonging to any of the selected categories will be included.",
)
tag = blocks.ChoiceBlock(
label="Filter by Tag",
required=False,
choices=get_tags,
help_text="If selected, only incidents with the chosen tag will be included.",
)
lower_date = blocks.DateBlock(
label="Filter by Date, lower bound",
required=False,
help_text="If set, no incidents before this date will be included.",
)
upper_date = blocks.DateBlock(
label="Filter by Date, upper bound",
required=False,
help_text="If set, no incidents after this date will be included.",
)
states = blocks.MultipleChoiceBlock(
label="Filter by State",
required=False,
choices=get_states,
help_text="If selected, only incidents in the chosen states will be included.",
)
class BubbleMapChartValue(ChartValue):
options_schema = BubbleMapChartOptionsSchema
chart_type = ChartType.BUBBLE_MAP
class VerticalBarChart(blocks.StructBlock):
title = blocks.CharBlock(required=False)
incident_set = SimpleIncidentSet()
time_period = blocks.ChoiceBlock(
label="Display by",
required=False,
choices=[("months", "Months"), ("years", "Years")],
help_text="Choose whether to display bars aggregated by months or years. If not provided, will default to months if there is less than two years of data, years if there is more than two years of data.",
)
description = blocks.TextBlock(
required=True,
help_text="Description for assistive technology users. "
"If the chart is demonstrating a specific trend, try to include that, "
'e.g., "Bar chart showing a decreasing number of assaults over the '
'course of 2023."',
)
group_by = blocks.ChoiceBlock(
label="Group Incidents By",
required=False,
choices=charts.IncidentBranches.choices,
default=None,
help_text="If selected, turns this vertical bar chart into a stacked bar chart with incidents grouped "
"by the selected classification.",
)
group_by_tag = blocks.ChoiceBlock(
label="Group Incidents By Tag",
required=False,
choices=get_tags,
default=None,
help_text="If selected, turns this vertical bar chart into a stacked bar chart with incidents grouped "
"by whether or not it has the tag selected. Note that if this field is selected, the group by selection above will be ignored.",
)
class Meta:
icon = "table"
template = "common/blocks/vertical_bar_chart.html"
value_class = charts.VerticalBarChartValue
class Media:
js = ["verticalBarChart"]
class TreeMapChart(blocks.StructBlock):
title = blocks.CharBlock(required=False)
incident_set = SimpleIncidentSet()
description = blocks.TextBlock(
required=True,
help_text="Description for assistive technology users. "
"If the chart is demonstrating a specific trend, try to include that, "
'e.g., "Bar chart showing a decreasing number of assaults over the '
'course of 2023."',
)
group_by = blocks.ChoiceBlock(
label="Group Incidents By",
required=True,
choices=charts.IncidentBranches.choices,
default=charts.IncidentBranches.CATEGORIES,
)
class Meta:
icon = "table"
template = "common/blocks/tree_map_chart.html"
value_class = charts.TreeMapChartValue
class Media:
js = ["treeMapChart"]
class BubbleMapChart(blocks.StructBlock):
title = blocks.CharBlock(required=False)
incident_set = SimpleIncidentSet()
group_by = blocks.ChoiceBlock(
label="Group Incidents by",
required=True,
choices=[("state", "State"), ("city", "City")],
help_text="Choose whether to group by city or by state",
)
description = blocks.TextBlock(
required=True,
help_text="Description for assistive technology users. "
"If the chart is demonstrating a specific trend, try to include that, "
'e.g., "Bar chart showing a decreasing number of assaults over the '
'course of 2023."',
)
domain_max = blocks.IntegerBlock(
label="Maximum bubble scale",
required=False,
min_value=1,
help_text=(
"Optional. Set the value that produces the max bubble size. Use across maps to make visually comparable. Note: set ≥ max incident count as this clamps the size of any point above set value."
),
)
class Meta:
icon = "table"
template = "common/blocks/bubble_map_chart.html"
value_class = BubbleMapChartValue
class Media:
js = ["bubbleMapChart"]
class HexbinMapChartValue(ChartValue):
options_schema = HexbinMapChartOptionsSchema
chart_type = ChartType.HEXBIN_MAP
class HexbinMapChart(blocks.StructBlock):
title = blocks.CharBlock(required=False)
incident_set = SimpleIncidentSet()
description = blocks.TextBlock(
required=True,
help_text="Description for assistive technology users. "
"If the chart is demonstrating a specific trend, try to include that, "
'e.g., "Bar chart showing a decreasing number of assaults over the '
'course of 2023."',
)
class Meta:
icon = "table"
template = "common/blocks/hexbin_map_chart.html"
value_class = HexbinMapChartValue
class Media:
js = ["hexbinMapChart"]