wagtail-table 0.1.0a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- wagtail_table/__init__.py +1 -0
- wagtail_table/blocks.py +91 -0
- wagtail_table/data.py +157 -0
- wagtail_table/rendering.py +133 -0
- wagtail_table/static/wagtail_table/THIRD_PARTY_LICENSES.txt +569 -0
- wagtail_table/static/wagtail_table/table-public.css +9 -0
- wagtail_table/static/wagtail_table/table.css +2 -0
- wagtail_table/static/wagtail_table/table.js +108 -0
- wagtail_table/templates/wagtail_table/rows.html +19 -0
- wagtail_table/templates/wagtail_table/table.html +16 -0
- wagtail_table/templates/wagtail_table/widgets/table.html +7 -0
- wagtail_table/widgets.py +102 -0
- wagtail_table-0.1.0a1.dist-info/METADATA +182 -0
- wagtail_table-0.1.0a1.dist-info/RECORD +16 -0
- wagtail_table-0.1.0a1.dist-info/WHEEL +4 -0
- wagtail_table-0.1.0a1.dist-info/licenses/LICENSE +28 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""A native Tiptap table editor for Wagtail StreamField."""
|
wagtail_table/blocks.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
|
|
4
|
+
from django import forms
|
|
5
|
+
from django.core.exceptions import ValidationError
|
|
6
|
+
from django.utils.functional import cached_property
|
|
7
|
+
from django.utils.translation import gettext_lazy as _
|
|
8
|
+
from wagtail.blocks import FieldBlock
|
|
9
|
+
|
|
10
|
+
from .data import MAX_JSON_LENGTH, validate_value
|
|
11
|
+
from .rendering import table_context
|
|
12
|
+
from .widgets import TableInput
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TableJSONField(forms.JSONField):
|
|
18
|
+
def validate(self, value):
|
|
19
|
+
super().validate(value)
|
|
20
|
+
validate_value(value)
|
|
21
|
+
|
|
22
|
+
def to_python(self, value):
|
|
23
|
+
if isinstance(value, str) and len(value) > MAX_JSON_LENGTH:
|
|
24
|
+
raise ValidationError(_("The table document is too large."))
|
|
25
|
+
try:
|
|
26
|
+
return super().to_python(value)
|
|
27
|
+
except RecursionError as error:
|
|
28
|
+
raise ValidationError(
|
|
29
|
+
_("The table document is nested too deeply.")
|
|
30
|
+
) from error
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TableBlock(FieldBlock):
|
|
34
|
+
def __init__(self, required=True, help_text=None, **kwargs):
|
|
35
|
+
self.field_options = {"required": required, "help_text": help_text}
|
|
36
|
+
super().__init__(**kwargs)
|
|
37
|
+
|
|
38
|
+
@cached_property
|
|
39
|
+
def field(self):
|
|
40
|
+
return TableJSONField(widget=TableInput(), **self.field_options)
|
|
41
|
+
|
|
42
|
+
def get_form_state(self, value):
|
|
43
|
+
# StreamField expects JSON state; the underlying input submits a JSON string.
|
|
44
|
+
# Invalid POST data stays intact so validation can report it without loss.
|
|
45
|
+
if isinstance(value, str):
|
|
46
|
+
try:
|
|
47
|
+
parsed = self.field.to_python(value)
|
|
48
|
+
except ValidationError:
|
|
49
|
+
return value
|
|
50
|
+
else:
|
|
51
|
+
parsed = value
|
|
52
|
+
try:
|
|
53
|
+
validate_value(parsed)
|
|
54
|
+
except ValidationError:
|
|
55
|
+
return value if isinstance(value, str) else json.dumps(value)
|
|
56
|
+
return parsed
|
|
57
|
+
|
|
58
|
+
def get_context(self, value, parent_context=None):
|
|
59
|
+
context = super().get_context(value, parent_context=parent_context)
|
|
60
|
+
context["rows"] = []
|
|
61
|
+
if value is None:
|
|
62
|
+
return context
|
|
63
|
+
try:
|
|
64
|
+
validate_value(value)
|
|
65
|
+
except ValidationError:
|
|
66
|
+
logger.warning("Refusing to render an invalid wagtail-table document")
|
|
67
|
+
return context
|
|
68
|
+
context.update(table_context(value))
|
|
69
|
+
return context
|
|
70
|
+
|
|
71
|
+
def get_searchable_content(self, value):
|
|
72
|
+
try:
|
|
73
|
+
validate_value(value)
|
|
74
|
+
except ValidationError:
|
|
75
|
+
return []
|
|
76
|
+
if value is None:
|
|
77
|
+
return []
|
|
78
|
+
metadata = [value.get("caption", ""), value.get("description", "")]
|
|
79
|
+
return [text for text in metadata if text] + [
|
|
80
|
+
text["text"]
|
|
81
|
+
for row in value["table"]["content"]
|
|
82
|
+
for cell in row.get("content", [])
|
|
83
|
+
for paragraph in cell["content"]
|
|
84
|
+
for text in paragraph.get("content", [])
|
|
85
|
+
if text["type"] == "text"
|
|
86
|
+
]
|
|
87
|
+
|
|
88
|
+
class Meta:
|
|
89
|
+
icon = "table"
|
|
90
|
+
template = "wagtail_table/table.html"
|
|
91
|
+
default = None
|
wagtail_table/data.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Validate the small native node vocabulary supported by the Python renderer."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
from django.core.exceptions import ValidationError
|
|
6
|
+
from django.utils.translation import gettext_lazy as _
|
|
7
|
+
|
|
8
|
+
MAX_JSON_LENGTH = 2_000_000
|
|
9
|
+
MAX_ROWS = 1000
|
|
10
|
+
MAX_COLUMNS = 100
|
|
11
|
+
MAX_CELLS = 10_000
|
|
12
|
+
|
|
13
|
+
CHILD_TYPES = {
|
|
14
|
+
"table": ("tableRow",),
|
|
15
|
+
"tableRow": ("tableCell", "tableHeader"),
|
|
16
|
+
"tableCell": ("paragraph",),
|
|
17
|
+
"tableHeader": ("paragraph",),
|
|
18
|
+
"paragraph": ("text", "hardBreak"),
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def validate_value(value):
|
|
23
|
+
"""Reject unsupported data rather than silently dropping content on save."""
|
|
24
|
+
if value is None:
|
|
25
|
+
return
|
|
26
|
+
try:
|
|
27
|
+
if len(json.dumps(value)) > MAX_JSON_LENGTH:
|
|
28
|
+
raise ValidationError(_("The table document is too large."))
|
|
29
|
+
except (RecursionError, TypeError, ValueError) as error:
|
|
30
|
+
raise ValidationError(_("Enter a supported table document.")) from error
|
|
31
|
+
validate_metadata(value)
|
|
32
|
+
table = value.get("table")
|
|
33
|
+
validate_node(table, ("table",))
|
|
34
|
+
validate_grid(table["content"])
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def validate_metadata(value):
|
|
38
|
+
if not isinstance(value, dict) or set(value) - {
|
|
39
|
+
"version",
|
|
40
|
+
"table",
|
|
41
|
+
"caption",
|
|
42
|
+
"description",
|
|
43
|
+
}:
|
|
44
|
+
raise ValidationError(_("Enter a supported table document."))
|
|
45
|
+
if type(value.get("version")) is not int or value["version"] != 1:
|
|
46
|
+
raise ValidationError(_("This table document version is not supported."))
|
|
47
|
+
if not all(
|
|
48
|
+
isinstance(value.get(key, ""), str) for key in ("caption", "description")
|
|
49
|
+
):
|
|
50
|
+
raise ValidationError(_("Table caption and description must be text."))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def validate_node(node, allowed_types):
|
|
54
|
+
if not isinstance(node, dict) or node.get("type") not in allowed_types:
|
|
55
|
+
raise ValidationError(_("The table contains an unsupported content type."))
|
|
56
|
+
node_type = node["type"]
|
|
57
|
+
if node_type in {"text", "hardBreak"}:
|
|
58
|
+
validate_inline(node)
|
|
59
|
+
return
|
|
60
|
+
if set(node) - {"type", "content", "attrs"}:
|
|
61
|
+
raise ValidationError(_("The table contains unsupported formatting."))
|
|
62
|
+
validate_attrs(node_type, node.get("attrs", {}))
|
|
63
|
+
for child in validate_children(node):
|
|
64
|
+
validate_node(child, CHILD_TYPES[node_type])
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def validate_children(node):
|
|
68
|
+
content = node.get("content", [])
|
|
69
|
+
if not isinstance(content, list) or len(content) > MAX_CELLS:
|
|
70
|
+
raise ValidationError(_("The table contains too much content."))
|
|
71
|
+
if not content and node["type"] not in {"paragraph", "tableRow"}:
|
|
72
|
+
raise ValidationError(_("Table rows and cells cannot be missing."))
|
|
73
|
+
return content
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def validate_inline(node):
|
|
77
|
+
if node["type"] == "hardBreak":
|
|
78
|
+
if set(node) != {"type"}:
|
|
79
|
+
raise ValidationError(_("Unsupported line break attributes."))
|
|
80
|
+
return
|
|
81
|
+
if (
|
|
82
|
+
set(node) != {"type", "text"}
|
|
83
|
+
or not isinstance(node["text"], str)
|
|
84
|
+
or not node["text"]
|
|
85
|
+
):
|
|
86
|
+
raise ValidationError(_("Table text must be plain text."))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def validate_attrs(node_type, attrs):
|
|
90
|
+
if not isinstance(attrs, dict):
|
|
91
|
+
raise ValidationError(_("Invalid table attributes."))
|
|
92
|
+
if node_type not in {"tableCell", "tableHeader"}:
|
|
93
|
+
if attrs:
|
|
94
|
+
raise ValidationError(_("Unsupported table attributes."))
|
|
95
|
+
return
|
|
96
|
+
if set(attrs) - {"rowspan", "colspan", "colwidth", "align", "verticalAlign"}:
|
|
97
|
+
raise ValidationError(_("Unsupported cell attributes."))
|
|
98
|
+
validate_alignment(attrs)
|
|
99
|
+
validate_spans(attrs)
|
|
100
|
+
validate_colwidth(attrs)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def validate_alignment(attrs):
|
|
104
|
+
if attrs.get("align") not in (None, "left", "center", "right"):
|
|
105
|
+
raise ValidationError(_("Unsupported cell alignment."))
|
|
106
|
+
if attrs.get("verticalAlign") not in (None, "top", "middle", "bottom"):
|
|
107
|
+
raise ValidationError(_("Unsupported vertical alignment."))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def validate_spans(attrs):
|
|
111
|
+
for key, limit in (("rowspan", MAX_ROWS), ("colspan", MAX_COLUMNS)):
|
|
112
|
+
span = attrs.get(key, 1)
|
|
113
|
+
if type(span) is not int or not 1 <= span <= limit:
|
|
114
|
+
raise ValidationError(_("Invalid cell span."))
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def validate_colwidth(attrs):
|
|
118
|
+
widths = attrs.get("colwidth")
|
|
119
|
+
if widths is None:
|
|
120
|
+
return
|
|
121
|
+
if not isinstance(widths, list) or len(widths) != attrs.get("colspan", 1):
|
|
122
|
+
raise ValidationError(_("Invalid column widths."))
|
|
123
|
+
if any(type(width) is not int or not 0 <= width <= 10_000 for width in widths):
|
|
124
|
+
raise ValidationError(_("Invalid column widths."))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def validate_grid(rows):
|
|
128
|
+
"""Inspect geometry only; ProseMirror owns all table manipulation."""
|
|
129
|
+
if len(rows) > MAX_ROWS:
|
|
130
|
+
raise ValidationError(_("The table has too many rows."))
|
|
131
|
+
occupied = set()
|
|
132
|
+
width = 0
|
|
133
|
+
for row_index, row in enumerate(rows):
|
|
134
|
+
column = 0
|
|
135
|
+
for cell in row.get("content", []):
|
|
136
|
+
while (row_index, column) in occupied:
|
|
137
|
+
column += 1
|
|
138
|
+
attrs = cell.get("attrs", {})
|
|
139
|
+
right = column + attrs.get("colspan", 1)
|
|
140
|
+
bottom = row_index + attrs.get("rowspan", 1)
|
|
141
|
+
fill_rectangle(occupied, row_index, column, bottom, right, len(rows))
|
|
142
|
+
column = right
|
|
143
|
+
width = max(width, right)
|
|
144
|
+
if not width or len(occupied) != len(rows) * width:
|
|
145
|
+
raise ValidationError(_("Table rows must form a complete rectangle."))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def fill_rectangle(occupied, top, left, bottom, right, row_count):
|
|
149
|
+
if right > MAX_COLUMNS or bottom > row_count:
|
|
150
|
+
raise ValidationError(_("Cell spans extend outside the table."))
|
|
151
|
+
for row in range(top, bottom):
|
|
152
|
+
for column in range(left, right):
|
|
153
|
+
if (row, column) in occupied:
|
|
154
|
+
raise ValidationError(_("Table cells overlap."))
|
|
155
|
+
occupied.add((row, column))
|
|
156
|
+
if len(occupied) > MAX_CELLS:
|
|
157
|
+
raise ValidationError(_("The table has too many cells."))
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Build safe template data and conservative associations for edge headers."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from uuid import uuid4
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass
|
|
8
|
+
class Cell:
|
|
9
|
+
header: bool
|
|
10
|
+
content: list
|
|
11
|
+
row: int
|
|
12
|
+
column: int
|
|
13
|
+
rowspan: int
|
|
14
|
+
colspan: int
|
|
15
|
+
classes: str
|
|
16
|
+
id: str = ""
|
|
17
|
+
scope: str = ""
|
|
18
|
+
headers: str = ""
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def bottom(self):
|
|
22
|
+
return self.row + self.rowspan
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def right(self):
|
|
26
|
+
return self.column + self.colspan
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def table_context(value):
|
|
30
|
+
"""Input has already passed server validation; no saved HTML is rendered."""
|
|
31
|
+
prefix = f"table-{uuid4().hex}"
|
|
32
|
+
rows = layout_rows(value["table"]["content"])
|
|
33
|
+
cells = [cell for row in rows for cell in row]
|
|
34
|
+
leading = leading_header_rows(rows)
|
|
35
|
+
associate_headers(cells, leading, prefix)
|
|
36
|
+
# A row span may not cross HTML row-group boundaries. Keep a single tbody
|
|
37
|
+
# when a header reaches into the body; do not change or split saved cells.
|
|
38
|
+
head_count = leading
|
|
39
|
+
if any(cell.row < leading < cell.bottom for cell in cells):
|
|
40
|
+
head_count = 0
|
|
41
|
+
return {
|
|
42
|
+
"rows": rows,
|
|
43
|
+
"head_rows": rows[:head_count],
|
|
44
|
+
"body_rows": rows[head_count:],
|
|
45
|
+
"caption": value.get("caption", ""),
|
|
46
|
+
"description": value.get("description", ""),
|
|
47
|
+
"description_id": f"{prefix}-description",
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def layout_rows(rows):
|
|
52
|
+
"""Read cell coordinates for rendering; table edits remain ProseMirror's job."""
|
|
53
|
+
occupied = set()
|
|
54
|
+
result = []
|
|
55
|
+
for row_index, row in enumerate(rows):
|
|
56
|
+
cells = []
|
|
57
|
+
column = 0
|
|
58
|
+
for node in row.get("content", []):
|
|
59
|
+
while (row_index, column) in occupied:
|
|
60
|
+
column += 1
|
|
61
|
+
attrs = node.get("attrs", {})
|
|
62
|
+
cell = Cell(
|
|
63
|
+
header=node["type"] == "tableHeader",
|
|
64
|
+
content=node["content"],
|
|
65
|
+
row=row_index,
|
|
66
|
+
column=column,
|
|
67
|
+
rowspan=attrs.get("rowspan", 1),
|
|
68
|
+
colspan=attrs.get("colspan", 1),
|
|
69
|
+
classes=alignment_classes(attrs),
|
|
70
|
+
)
|
|
71
|
+
cells.append(cell)
|
|
72
|
+
occupied.update(
|
|
73
|
+
(r, c)
|
|
74
|
+
for r in range(cell.row, cell.bottom)
|
|
75
|
+
for c in range(cell.column, cell.right)
|
|
76
|
+
)
|
|
77
|
+
column = cell.right
|
|
78
|
+
result.append(cells)
|
|
79
|
+
return result
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def alignment_classes(attrs):
|
|
83
|
+
classes = []
|
|
84
|
+
if attrs.get("align"):
|
|
85
|
+
classes.append(f"wagtail-table-align-{attrs['align']}")
|
|
86
|
+
if attrs.get("verticalAlign"):
|
|
87
|
+
classes.append(f"wagtail-table-valign-{attrs['verticalAlign']}")
|
|
88
|
+
return " ".join(classes)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def leading_header_rows(rows):
|
|
92
|
+
count = 0
|
|
93
|
+
for row in rows:
|
|
94
|
+
if not row or not all(cell.header for cell in row):
|
|
95
|
+
break
|
|
96
|
+
count += 1
|
|
97
|
+
return count
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def associate_headers(cells, leading, prefix):
|
|
101
|
+
headers = [cell for cell in cells if cell.header]
|
|
102
|
+
row_headers = [cell for cell in headers if cell.column == 0 and cell.row >= leading]
|
|
103
|
+
column_headers = [
|
|
104
|
+
cell
|
|
105
|
+
for cell in headers
|
|
106
|
+
if cell.row < leading
|
|
107
|
+
and cell.bottom <= leading
|
|
108
|
+
and not (cell.column == 0 and row_headers)
|
|
109
|
+
]
|
|
110
|
+
for cell in headers:
|
|
111
|
+
cell.id = f"{prefix}-r{cell.row}-c{cell.column}"
|
|
112
|
+
for header in row_headers:
|
|
113
|
+
header.scope = "row" if header.rowspan == 1 else ""
|
|
114
|
+
for header in column_headers:
|
|
115
|
+
header.scope = "col" if header.colspan == 1 else ""
|
|
116
|
+
for cell in cells:
|
|
117
|
+
if cell.header:
|
|
118
|
+
continue
|
|
119
|
+
cell.headers = " ".join(
|
|
120
|
+
header.id
|
|
121
|
+
for header in column_headers
|
|
122
|
+
if header.bottom <= cell.row
|
|
123
|
+
and header.column < cell.right
|
|
124
|
+
and cell.column < header.right
|
|
125
|
+
)
|
|
126
|
+
row_ids = [
|
|
127
|
+
header.id
|
|
128
|
+
for header in row_headers
|
|
129
|
+
if header.right <= cell.column
|
|
130
|
+
and header.row < cell.bottom
|
|
131
|
+
and cell.row < header.bottom
|
|
132
|
+
]
|
|
133
|
+
cell.headers = " ".join(filter(None, [cell.headers, *row_ids]))
|