-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathplugin_rendering.py
More file actions
296 lines (250 loc) · 10.5 KB
/
plugin_rendering.py
File metadata and controls
296 lines (250 loc) · 10.5 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
import json
from typing import Any
from collections.abc import Iterable
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.utils.html import escape, mark_safe
from cms.models import Placeholder
from cms.plugin_rendering import ContentRenderer
from cms.utils.plugins import get_plugins
from djangocms_rest.serializers.placeholders import PlaceholderSerializer
from djangocms_rest.serializers.plugins import (
get_auto_model_serializer,
resolve_plugin_serializer,
)
from djangocms_rest.serializers.utils.cache import (
get_placeholder_rest_cache,
set_placeholder_rest_cache,
)
def serialize_cms_plugin(instance: Any | None, context: dict[str, Any]) -> dict[str, Any] | None:
if not instance or not hasattr(instance, "get_plugin_instance"):
return None
plugin_instance, plugin = instance.get_plugin_instance()
model_cls = plugin_instance.__class__
serializer_cls = resolve_plugin_serializer(plugin, model_cls)
serializer_cls = serializer_cls or get_auto_model_serializer(model_cls)
return serializer_cls(plugin_instance, context=context).data
# Template for a collapsable key-value pair
DETAILS_TEMPLATE = (
'<details open><summary><span class="key">"{key}"</span>: {open}</summary>'
'<div class="indent">{value}</div></details>{close}'
)
# Template for a collapsable object/list
OBJ_TEMPLATE = "<details open><summary>{open}</summary>" '<div class="indent">{value}</div></details>{close}'
# Tempalte for a non-collasable object/list
FIXED_TEMPLATE = '{open}<div class="indent">{value}</div>{close}'
# Tempalte for a single line key-value pair
SIMPLE_TEMPLATE = '<span class="key">"{key}"</span>: {value}'
def escapestr(s: str) -> str:
"""
Escape a string for safe HTML rendering.
"""
return escape(json.dumps(s)[1:-1]) # Remove quotes added by json.dumps
def is_valid_url(url):
validator = URLValidator()
try:
validator(url)
return True
except ValidationError:
return False
def highlight_data(json_data: Any, drop_frame: bool = False) -> str:
"""
Highlight single JSON data element.
"""
if isinstance(json_data, str):
classes = "str"
if len(json_data) > 60:
classes = "str ellipsis"
if is_valid_url(json_data):
return f'<span class="{ classes }">"<a href="{ json_data }">{escapestr(json_data)}</a>"</span>'
return f'<span class="{ classes }">"{escapestr(json_data)}"</span>'
if isinstance(json_data, bool):
return f'<span class="bool">{str(json_data).lower()}</span>'
if isinstance(json_data, (int, float)):
return f'<span class="num">{json_data}</span>'
if json_data is None:
return '<span class="null">null</span>'
if isinstance(json_data, dict):
if drop_frame:
return highlight_json(json_data)["value"] if json_data else "{}"
return OBJ_TEMPLATE.format(**highlight_json(json_data)) if json_data else "{}"
if isinstance(json_data, list):
if drop_frame:
return highlight_list(json_data)["value"] if json_data else "[]"
return OBJ_TEMPLATE.format(**highlight_list(json_data)) if json_data else "[]"
return f'<span class="obj">{json_data}</span>'
def highlight_list(json_data: list) -> dict[str, str]:
"""
Transforms a list of JSON data items into a dictionary containing HTML-formatted string representations.
Args:
json_data (list): A list of JSON-compatible data items to be highlighted.
Returns:
dict[str, str]: A dictionary with keys 'open', 'close', and 'value', where 'value' is a string of highlighted items separated by ',<br>'.
"""
items = [highlight_data(item) for item in json_data]
return {
"open": "[",
"close": "]",
"value": ",<br>".join(items),
}
def highlight_json(
json_data: dict[str, Any],
children: Iterable | None = None,
marker: str = "",
field: str = "children",
) -> dict[str, str]:
"""
Highlights and formats a JSON-like dictionary for display, optionally including child elements.
Args:
json_data (dict[str, Any]): The JSON data to be highlighted and formatted.
children (Iterable | None, optional): An iterable of child elements to include under the specified field. Defaults to None.
marker (str, optional): A string marker to append after the children. Defaults to "".
field (str, optional): The key under which children are added. Defaults to "children".
Returns:
dict[str, str]: A dictionary containing the formatted representation with keys 'open', 'close', and 'value'.
"""
has_children = children is not None
if field in json_data:
del json_data[field]
items = [
DETAILS_TEMPLATE.format(
key=escape(key),
value=highlight_data(value, drop_frame=True),
open="{" if isinstance(value, dict) else "[",
close="}" if isinstance(value, dict) else "]",
)
if isinstance(value, (dict, list)) and value
else SIMPLE_TEMPLATE.format(
key=escape(key),
value=highlight_data(value),
)
for key, value in json_data.items()
]
if has_children:
items.append(
DETAILS_TEMPLATE.format(
key=escape(field),
value=",".join(children) + marker,
open="[",
close="]",
)
)
return {
"open": "{",
"close": "}",
"value": ",<br>".join(items),
}
class RESTRenderer(ContentRenderer):
"""
A custom renderer that uses the serialize_cms_plugin function to render
CMS plugins in a RESTful way.
"""
placeholder_edit_template = "{content}{plugin_js}{placeholder_js}"
def render_plugin(self, instance, context, placeholder=None, editable: bool = False):
"""
Render a CMS plugin instance using the serialize_cms_plugin function.
"""
data = serialize_cms_plugin(instance, context) or {}
children = [
self.render_plugin(child, context, placeholder=placeholder, editable=editable)
for child in getattr(instance, "child_plugin_instances", [])
] or None
content = OBJ_TEMPLATE.format(**highlight_json(data, children=children))
if editable:
content = self.plugin_edit_template.format(
pk=instance.pk,
placeholder=instance.placeholder_id,
content=content,
position=instance.position,
)
placeholder_cache = self._rendered_plugins_by_placeholder.setdefault(placeholder.pk, {})
placeholder_cache.setdefault("plugins", []).append(instance)
return mark_safe(content)
def render_plugins(self, placeholder, language, context, editable=False, template=None):
yield "<div class='rest-placeholder' data-placeholder='{placeholder}' data-language='{language}'>".format(
placeholder=placeholder.slot,
language=language,
)
placeholder_data = PlaceholderSerializer(
instance=placeholder,
language=language,
request=context["request"],
render_plugins=False,
).data
yield FIXED_TEMPLATE.format(
placeholder_id=placeholder.pk,
**highlight_json(
placeholder_data,
children=self.get_plugins_and_placeholder_lot(
placeholder, language, context, editable=editable, template=template
),
marker=f'<div class="cms-placeholder cms-placeholder-{placeholder.pk}"></div>',
field="content",
),
)
yield "</div>"
def get_plugins_and_placeholder_lot(
self, placeholder, language, context, editable=False, template=None
) -> Iterable[str]:
yield from super().render_plugins(placeholder, language, context, editable=editable, template=template)
def serialize_placeholder(self, placeholder, context, language, use_cache=True):
context.update({"request": self.request})
if use_cache and placeholder.cache_placeholder:
use_cache = self.placeholder_cache_is_enabled()
else:
use_cache = False
if use_cache:
cached_value = get_placeholder_rest_cache(
placeholder,
lang=language,
site_id=get_current_site(self.request).pk,
request=self.request,
)
else:
cached_value = None
if cached_value is not None:
# User has opted to use the cache
# and there is something in the cache
return cached_value["content"]
plugin_content = self.serialize_plugins(
placeholder,
language=language,
context=context,
)
if use_cache:
set_placeholder_rest_cache(
placeholder,
lang=language,
site_id=get_current_site(self.request).pk,
content=plugin_content,
request=self.request,
)
if placeholder.pk not in self._rendered_placeholders:
# First time this placeholder is rendered
self._rendered_placeholders[placeholder.pk] = plugin_content
return plugin_content
def serialize_plugins(self, placeholder: Placeholder, language: str, context: dict) -> list:
plugins = get_plugins(
self.request,
placeholder=placeholder,
lang=language,
template=None,
)
def serialize_children(child_plugins):
children_list = []
for child_plugin in child_plugins:
child_content = serialize_cms_plugin(child_plugin, context)
if getattr(child_plugin, "child_plugin_instances", None):
child_content["children"] = serialize_children(child_plugin.child_plugin_instances)
if child_content:
children_list.append(child_content)
return children_list
results = []
for plugin in plugins:
plugin_content = serialize_cms_plugin(plugin, context)
if getattr(plugin, "child_plugin_instances", None):
plugin_content["children"] = serialize_children(plugin.child_plugin_instances)
if plugin_content:
results.append(plugin_content)
return results