edwh-editorjs 2.0.0__tar.gz → 2.0.0b1__tar.gz

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.
Files changed (42) hide show
  1. edwh_editorjs-2.0.0b1/CHANGELOG.md +30 -0
  2. {edwh_editorjs-2.0.0 → edwh_editorjs-2.0.0b1}/LICENSE +0 -1
  3. edwh_editorjs-2.0.0b1/PKG-INFO +104 -0
  4. edwh_editorjs-2.0.0b1/README.md +79 -0
  5. edwh_editorjs-2.0.0b1/pyeditorjs/__about__.py +1 -0
  6. edwh_editorjs-2.0.0b1/pyeditorjs/__init__.py +30 -0
  7. edwh_editorjs-2.0.0b1/pyeditorjs/blocks.py +313 -0
  8. edwh_editorjs-2.0.0b1/pyeditorjs/exceptions.py +19 -0
  9. edwh_editorjs-2.0.0b1/pyeditorjs/parser.py +75 -0
  10. {edwh_editorjs-2.0.0 → edwh_editorjs-2.0.0b1}/pyproject.toml +7 -9
  11. edwh_editorjs-2.0.0b1/scripts/build_documentation.sh +4 -0
  12. edwh_editorjs-2.0.0b1/scripts/compile_everything.sh +4 -0
  13. edwh_editorjs-2.0.0b1/scripts/compile_for_pypi.sh +4 -0
  14. edwh_editorjs-2.0.0b1/tests/test_parser.py +42 -0
  15. edwh_editorjs-2.0.0/CHANGELOG.md +0 -60
  16. edwh_editorjs-2.0.0/PKG-INFO +0 -28
  17. edwh_editorjs-2.0.0/README.md +0 -2
  18. edwh_editorjs-2.0.0/editorjs/__about__.py +0 -1
  19. edwh_editorjs-2.0.0/editorjs/__init__.py +0 -5
  20. edwh_editorjs-2.0.0/editorjs/blocks.py +0 -670
  21. edwh_editorjs-2.0.0/editorjs/core.py +0 -119
  22. edwh_editorjs-2.0.0/editorjs/exceptions.py +0 -3
  23. edwh_editorjs-2.0.0/editorjs/helpers.py +0 -5
  24. edwh_editorjs-2.0.0/editorjs/types.py +0 -43
  25. edwh_editorjs-2.0.0/htmlcov/.gitignore +0 -2
  26. edwh_editorjs-2.0.0/htmlcov/class_index.html +0 -259
  27. edwh_editorjs-2.0.0/htmlcov/favicon_32_cb_58284776.png +0 -0
  28. edwh_editorjs-2.0.0/htmlcov/function_index.html +0 -395
  29. edwh_editorjs-2.0.0/htmlcov/index.html +0 -132
  30. edwh_editorjs-2.0.0/htmlcov/keybd_closed_cb_ce680311.png +0 -0
  31. edwh_editorjs-2.0.0/htmlcov/status.json +0 -1
  32. edwh_editorjs-2.0.0/htmlcov/style_cb_8e611ae1.css +0 -337
  33. edwh_editorjs-2.0.0/htmlcov/z_a93c8aeb4b8fa1f9___init___py.html +0 -125
  34. edwh_editorjs-2.0.0/htmlcov/z_a93c8aeb4b8fa1f9_blocks_py.html +0 -406
  35. edwh_editorjs-2.0.0/htmlcov/z_a93c8aeb4b8fa1f9_exceptions_py.html +0 -116
  36. edwh_editorjs-2.0.0/htmlcov/z_a93c8aeb4b8fa1f9_parser_py.html +0 -172
  37. edwh_editorjs-2.0.0/tests/test_core.py +0 -112
  38. {edwh_editorjs-2.0.0 → edwh_editorjs-2.0.0b1}/.github/workflows/build_documentation.yml +0 -0
  39. {edwh_editorjs-2.0.0 → edwh_editorjs-2.0.0b1}/.github/workflows/publish_to_pypi.yml +0 -0
  40. {edwh_editorjs-2.0.0 → edwh_editorjs-2.0.0b1}/.github/workflows/pytest.yml +0 -0
  41. {edwh_editorjs-2.0.0 → edwh_editorjs-2.0.0b1}/.gitignore +0 -0
  42. /edwh_editorjs-2.0.0/tests/__init__.py → /edwh_editorjs-2.0.0b1/requirements.txt +0 -0
@@ -0,0 +1,30 @@
1
+ # Changelog
2
+
3
+ <!--next-version-placeholder-->
4
+
5
+ ## v2.0.0-beta.1 (2024-11-06)
6
+
7
+
8
+
9
+ ## v1.1.0 (2024-10-31)
10
+
11
+ ### Feature
12
+
13
+ * Expose _sanitize via EditorJSBlock.sanitize for external usage ([`7daa67c`](https://github.com/educationwarehouse/edwh-editorjs/commit/7daa67c90440510c83b573c22edf377cc2fd801f))
14
+
15
+ ### Documentation
16
+
17
+ * Added section on defining new custom blocks ([`51d7720`](https://github.com/educationwarehouse/edwh-editorjs/commit/51d77208d4f8156e895de914f41bdeb882a508c0))
18
+
19
+ ## v1.0.1 (2024-10-31)
20
+
21
+ ### Documentation
22
+
23
+ * Updated README ([`18d0216`](https://github.com/educationwarehouse/edwh-editorjs/commit/18d021629bcb223b89a9731e9ad8c574248f75c7))
24
+
25
+ ## v1.0.0 (2024-10-31)
26
+
27
+ ### Feature
28
+
29
+ * Implemented more blocks (raw, warning, code, table, quote) ([`fb93bd9`](https://github.com/educationwarehouse/edwh-editorjs/commit/fb93bd959f06fa86bc23c9bfc51a8b7fddfc65f2))
30
+ * Refactor to Registry Pattern so new block can be easily added ([`b06c86d`](https://github.com/educationwarehouse/edwh-editorjs/commit/b06c86da623dd2a2d92f7c48353a1f3208fb5749))
@@ -1,7 +1,6 @@
1
1
  MIT License
2
2
 
3
3
  Copyright (c) 2021 SKevo
4
- Copyright (c) 2024 Education Warehouse
5
4
 
6
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
7
6
  of this software and associated documentation files (the "Software"), to deal
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.3
2
+ Name: edwh-editorjs
3
+ Version: 2.0.0b1
4
+ Summary: pyEditorJS
5
+ Project-URL: Homepage, https://github.com/educationwarehouse/edwh-EditorJS
6
+ Author-email: SKevo <skevo.cw@gmail.com>, Robin van der Noord <robin.vdn@educationwarehouse.nl>
7
+ License: MIT
8
+ License-File: LICENSE
9
+ Keywords: bleach,clean,editor,editor.js,html,javascript,json,parser,wysiwyg
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: bleach
19
+ Provides-Extra: dev
20
+ Requires-Dist: edwh; extra == 'dev'
21
+ Requires-Dist: hatch; extra == 'dev'
22
+ Requires-Dist: su6[all]; extra == 'dev'
23
+ Requires-Dist: types-bleach; extra == 'dev'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # edwh-editorjs
27
+
28
+ A minimal, fast Python 3.10+ package for parsing [Editor.js](https://editorjs.io) content.
29
+ This package is a fork of [pyEditorJS by SKevo](https://github.com/SKevo18/pyEditorJS) with additional capabilities.
30
+
31
+ ## New Features
32
+
33
+ - Expanded support for additional block types: Quote, Table, Code, Warning, and Raw blocks
34
+ - Issues a warning if an unknown block type is encountered, rather than ignoring it
35
+ - Adds a `strict` mode, raising an `EditorJSUnsupportedBlock` exception for unknown block types when `strict=True`
36
+ - Allows adding new blocks by decorating a subclass of `EditorJsParser` with `@block("name")`
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ pip install edwh-editorjs
42
+ ```
43
+
44
+ ## Usage
45
+
46
+ ### Quickstart
47
+
48
+ ```python
49
+ from pyeditorjs import EditorJsParser
50
+
51
+ editor_js_data = ... # your Editor.js JSON data
52
+ parser = EditorJsParser(editor_js_data) # initialize the parser
53
+
54
+ html = parser.html(sanitize=True) # `sanitize=True` uses the included `bleach` dependency
55
+ print(html) # your clean HTML
56
+ ```
57
+
58
+ ### Enforcing Strict Block Types
59
+
60
+ ```python
61
+ from pyeditorjs import EditorJsParser, EditorJSUnsupportedBlock
62
+
63
+ editor_js_data: dict = ...
64
+ parser = EditorJsParser(editor_js_data)
65
+
66
+ try:
67
+ html = parser.html(strict=True)
68
+ except EditorJSUnsupportedBlock as e:
69
+ print(f"Unsupported block type encountered: {e}")
70
+ ```
71
+
72
+ ### Adding a Custom Block
73
+
74
+ To add a custom block type, create a new class that subclasses `EditorJsBlock` and decorates it with `@block("name")`,
75
+ where `"name"` is the custom block type. Implement an `html` method to define how the block’s content should be
76
+ rendered. This method should accept a `sanitize` parameter and can access block data via `self.data`.
77
+
78
+ ```python
79
+ from pyeditorjs import EditorJsParser, EditorJsBlock, block
80
+
81
+ @block("custom")
82
+ class CustomBlock(EditorJsBlock):
83
+ def html(self, sanitize: bool = False) -> str:
84
+ # Access data with self.data and return the rendered HTML
85
+ content = self.data.get("something", "")
86
+ if sanitize:
87
+ content = self.sanitize(content)
88
+
89
+ return f"<div class='custom-block'>{content}</div>"
90
+
91
+ # Usage
92
+ class CustomEditorJsParser(EditorJsParser):
93
+ pass # Custom blocks are automatically detected
94
+
95
+ editor_js_data = ... # Editor.js JSON data with a "customBlock" type
96
+ parser = CustomEditorJsParser(editor_js_data)
97
+ html = parser.html()
98
+ print(html) # Includes rendered custom blocks
99
+ ```
100
+
101
+ ## Disclaimer
102
+
103
+ This is a community-provided project and is not affiliated with the Editor.js team.
104
+ Contributions, bug reports, and suggestions are welcome!
@@ -0,0 +1,79 @@
1
+ # edwh-editorjs
2
+
3
+ A minimal, fast Python 3.10+ package for parsing [Editor.js](https://editorjs.io) content.
4
+ This package is a fork of [pyEditorJS by SKevo](https://github.com/SKevo18/pyEditorJS) with additional capabilities.
5
+
6
+ ## New Features
7
+
8
+ - Expanded support for additional block types: Quote, Table, Code, Warning, and Raw blocks
9
+ - Issues a warning if an unknown block type is encountered, rather than ignoring it
10
+ - Adds a `strict` mode, raising an `EditorJSUnsupportedBlock` exception for unknown block types when `strict=True`
11
+ - Allows adding new blocks by decorating a subclass of `EditorJsParser` with `@block("name")`
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pip install edwh-editorjs
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ### Quickstart
22
+
23
+ ```python
24
+ from pyeditorjs import EditorJsParser
25
+
26
+ editor_js_data = ... # your Editor.js JSON data
27
+ parser = EditorJsParser(editor_js_data) # initialize the parser
28
+
29
+ html = parser.html(sanitize=True) # `sanitize=True` uses the included `bleach` dependency
30
+ print(html) # your clean HTML
31
+ ```
32
+
33
+ ### Enforcing Strict Block Types
34
+
35
+ ```python
36
+ from pyeditorjs import EditorJsParser, EditorJSUnsupportedBlock
37
+
38
+ editor_js_data: dict = ...
39
+ parser = EditorJsParser(editor_js_data)
40
+
41
+ try:
42
+ html = parser.html(strict=True)
43
+ except EditorJSUnsupportedBlock as e:
44
+ print(f"Unsupported block type encountered: {e}")
45
+ ```
46
+
47
+ ### Adding a Custom Block
48
+
49
+ To add a custom block type, create a new class that subclasses `EditorJsBlock` and decorates it with `@block("name")`,
50
+ where `"name"` is the custom block type. Implement an `html` method to define how the block’s content should be
51
+ rendered. This method should accept a `sanitize` parameter and can access block data via `self.data`.
52
+
53
+ ```python
54
+ from pyeditorjs import EditorJsParser, EditorJsBlock, block
55
+
56
+ @block("custom")
57
+ class CustomBlock(EditorJsBlock):
58
+ def html(self, sanitize: bool = False) -> str:
59
+ # Access data with self.data and return the rendered HTML
60
+ content = self.data.get("something", "")
61
+ if sanitize:
62
+ content = self.sanitize(content)
63
+
64
+ return f"<div class='custom-block'>{content}</div>"
65
+
66
+ # Usage
67
+ class CustomEditorJsParser(EditorJsParser):
68
+ pass # Custom blocks are automatically detected
69
+
70
+ editor_js_data = ... # Editor.js JSON data with a "customBlock" type
71
+ parser = CustomEditorJsParser(editor_js_data)
72
+ html = parser.html()
73
+ print(html) # Includes rendered custom blocks
74
+ ```
75
+
76
+ ## Disclaimer
77
+
78
+ This is a community-provided project and is not affiliated with the Editor.js team.
79
+ Contributions, bug reports, and suggestions are welcome!
@@ -0,0 +1 @@
1
+ __version__ = "2.0.0-beta.1"
@@ -0,0 +1,30 @@
1
+ from pathlib import Path
2
+
3
+ from .blocks import BLOCKS_MAP, EditorJsBlock, block
4
+ from .exceptions import EditorJsException, EditorJsParseError, EditorJSUnsupportedBlock
5
+ from .parser import EditorJsParser
6
+
7
+ __all__ = [
8
+ "EditorJsParser",
9
+ "EditorJsParseError",
10
+ "EditorJsException",
11
+ "EditorJSUnsupportedBlock",
12
+ "EditorJsBlock",
13
+ "block",
14
+ "BLOCKS_MAP",
15
+ ]
16
+
17
+
18
+ # Overwrite __doc__ with README, so that pdoc can render it:
19
+ README_PATH = Path(__file__).parent.parent.absolute() / Path("README.md")
20
+ try:
21
+ with open(README_PATH, "r", encoding="UTF-8") as readme:
22
+ __readme__ = readme.read()
23
+ except Exception:
24
+ __readme__ = "Failed to read README.md!" # fallback message, for example when there's no README
25
+
26
+ __doc__ = __readme__
27
+
28
+
29
+ if __name__ == "__main__":
30
+ _ = [EditorJsParser]
@@ -0,0 +1,313 @@
1
+ import abc
2
+ import typing as t
3
+ from dataclasses import dataclass
4
+
5
+ import bleach
6
+
7
+ from .exceptions import EditorJsParseError
8
+
9
+ __all__ = [
10
+ "block",
11
+ "BLOCKS_MAP",
12
+ "EditorJsBlock",
13
+ ]
14
+
15
+
16
+ def _sanitize(html: str) -> str:
17
+ return bleach.clean(
18
+ html,
19
+ tags=["b", "i", "u", "a", "mark", "code"],
20
+ attributes=["class", "data-placeholder", "href"],
21
+ )
22
+
23
+
24
+ BLOCKS_MAP: t.Dict[str, t.Type["EditorJsBlock"]] = {
25
+ # 'header': HeaderBlock,
26
+ # 'paragraph': ParagraphBlock,
27
+ # 'list': ListBlock,
28
+ # 'delimiter': DelimiterBlock,
29
+ # 'image': ImageBlock,
30
+ }
31
+
32
+
33
+ def block(_type: str):
34
+ def wrapper(cls: t.Type["EditorJsBlock"]):
35
+ BLOCKS_MAP[_type] = cls
36
+ return cls
37
+
38
+ return wrapper
39
+
40
+
41
+ @dataclass
42
+ class EditorJsBlock(abc.ABC):
43
+ """
44
+ A generic parsed Editor.js block
45
+ """
46
+
47
+ _data: dict
48
+ """The raw JSON data of the entire block"""
49
+
50
+ @classmethod
51
+ def sanitize(cls, html: str) -> str:
52
+ return _sanitize(html)
53
+
54
+ @property
55
+ def id(self) -> t.Optional[str]:
56
+ """
57
+ Returns ID of the block, generated client-side.
58
+ """
59
+
60
+ return self._data.get("id", None)
61
+
62
+ @property
63
+ def type(self) -> t.Optional[str]:
64
+ """
65
+ Returns the type of the block.
66
+ """
67
+
68
+ return self._data.get("type", None)
69
+
70
+ @property
71
+ def data(self) -> dict:
72
+ """
73
+ Returns the actual block data.
74
+ """
75
+
76
+ return self._data.get("data", {})
77
+
78
+ @abc.abstractmethod
79
+ def html(self, sanitize: bool = False) -> str:
80
+ """
81
+ Returns the HTML representation of the block.
82
+
83
+ ### Parameters:
84
+ - `sanitize` - if `True`, then the block's text/contents will be sanitized.
85
+ """
86
+
87
+ raise NotImplementedError()
88
+
89
+
90
+ @block("header")
91
+ class HeaderBlock(EditorJsBlock):
92
+ VALID_HEADER_LEVEL_RANGE = range(1, 7)
93
+ """Valid range for header levels. Default is `range(1, 7)` - so, `0` - `6`."""
94
+
95
+ @property
96
+ def text(self) -> str:
97
+ """
98
+ Returns the header's text.
99
+ """
100
+
101
+ return self.data.get("text", "")
102
+
103
+ @property
104
+ def level(self) -> int:
105
+ """
106
+ Returns the header's level (`0` - `6`).
107
+ """
108
+
109
+ _level = self.data.get("level", 1)
110
+
111
+ if not isinstance(_level, int) or _level not in self.VALID_HEADER_LEVEL_RANGE:
112
+ raise EditorJsParseError(f"`{_level}` is not a valid header level.")
113
+
114
+ return _level
115
+
116
+ def html(self, sanitize: bool = False) -> str:
117
+ text = self.text
118
+ if sanitize:
119
+ text = _sanitize(text)
120
+ return rf'<h{self.level} class="cdx-block ce-header">{text}</h{self.level}>'
121
+
122
+
123
+ @block("paragraph")
124
+ class ParagraphBlock(EditorJsBlock):
125
+ @property
126
+ def text(self) -> str:
127
+ """
128
+ The text content of the paragraph.
129
+ """
130
+
131
+ return self.data.get("text", "")
132
+
133
+ def html(self, sanitize: bool = False) -> str:
134
+ return rf'<p class="cdx-block ce-paragraph">{_sanitize(self.text) if sanitize else self.text}</p>'
135
+
136
+
137
+ @block("list")
138
+ class ListBlock(EditorJsBlock):
139
+ VALID_STYLES = ("unordered", "ordered")
140
+ """Valid list order styles."""
141
+
142
+ @property
143
+ def style(self) -> t.Optional[str]:
144
+ """
145
+ The style of the list. Can be `ordered` or `unordered`.
146
+ """
147
+
148
+ return self.data.get("style", None)
149
+
150
+ @property
151
+ def items(self) -> t.List[str]:
152
+ """
153
+ Returns the list's items, in raw format.
154
+ """
155
+
156
+ return self.data.get("items", [])
157
+
158
+ def html(self, sanitize: bool = False) -> str:
159
+ if self.style not in self.VALID_STYLES:
160
+ raise EditorJsParseError(f"`{self.style}` is not a valid list style.")
161
+
162
+ _items = [
163
+ f"<li>{_sanitize(item) if sanitize else item}</li>" for item in self.items
164
+ ]
165
+ _type = "ul" if self.style == "unordered" else "ol"
166
+ _items_html = "".join(_items)
167
+
168
+ return rf'<{_type} class="cdx-block cdx-list cdx-list--{self.style}">{_items_html}</{_type}>'
169
+
170
+
171
+ @block("delimiter")
172
+ class DelimiterBlock(EditorJsBlock):
173
+ def html(self, sanitize: bool = False) -> str:
174
+ return r'<div class="cdx-block ce-delimiter"></div>'
175
+
176
+
177
+ @block("image")
178
+ class ImageBlock(EditorJsBlock):
179
+ @property
180
+ def file_url(self) -> str:
181
+ """
182
+ URL of the image file.
183
+ """
184
+
185
+ return self.data.get("file", {}).get("url", "")
186
+
187
+ @property
188
+ def caption(self) -> str:
189
+ """
190
+ The image's caption.
191
+ """
192
+
193
+ return self.data.get("caption", "")
194
+
195
+ @property
196
+ def with_border(self) -> bool:
197
+ """
198
+ Whether the image has a border.
199
+ """
200
+
201
+ return self.data.get("withBorder", False)
202
+
203
+ @property
204
+ def stretched(self) -> bool:
205
+ """
206
+ Whether the image is stretched.
207
+ """
208
+
209
+ return self.data.get("stretched", False)
210
+
211
+ @property
212
+ def with_background(self) -> bool:
213
+ """
214
+ Whether the image has a background.
215
+ """
216
+
217
+ return self.data.get("withBackground", False)
218
+
219
+ def html(self, sanitize: bool = False) -> str:
220
+ if self.file_url.startswith("data:image/"):
221
+ _img = self.file_url
222
+ else:
223
+ _img = _sanitize(self.file_url) if sanitize else self.file_url
224
+
225
+ parts = [
226
+ rf'<div class="cdx-block image-tool image-tool--filled {"image-tool--stretched" if self.stretched else ""} {"image-tool--withBorder" if self.with_border else ""} {"image-tool--withBackground" if self.with_background else ""}">'
227
+ r'<div class="image-tool__image">',
228
+ r'<div class="image-tool__image-preloader"></div>',
229
+ rf'<img class="image-tool__image-picture" src="{_img}"/>',
230
+ r"</div>"
231
+ rf'<div class="image-tool__caption" data-placeholder="{_sanitize(self.caption) if sanitize else self.caption}"></div>'
232
+ r"</div>"
233
+ r"</div>",
234
+ ]
235
+
236
+ return "".join(parts)
237
+
238
+
239
+ @block("quote")
240
+ class QuoteBlock(EditorJsBlock):
241
+ def html(self, sanitize: bool = False) -> str:
242
+ quote = self.data.get("text", "")
243
+ caption = self.data.get("caption", "")
244
+ if sanitize:
245
+ quote = _sanitize(quote)
246
+ caption = _sanitize(caption)
247
+ _alignment = self.data.get("alignment", "left") # todo
248
+ return f"""
249
+ <blockquote class="cdx-block cdx-quote">
250
+ <div class="cdx-input cdx-quote__text">{quote}</div>
251
+ <cite class="cdx-input cdx-quote__caption">{caption}</cite>
252
+ </blockquote>
253
+ """
254
+
255
+
256
+ @block("table")
257
+ class TableBlock(EditorJsBlock):
258
+ def html(self, sanitize: bool = False) -> str:
259
+ content = self.data.get("content", [])
260
+ _stretched = self.data.get("stretched", False) # todo
261
+ _with_headings = self.data.get("withHeadings", False) # todo
262
+
263
+ html_table = '<table class="tc-table">'
264
+
265
+ # Add content rows
266
+ for row in content:
267
+ html_table += '<tr class="tc-row">'
268
+ for cell in row:
269
+ html_table += (
270
+ f'<td class="tc-cell">{_sanitize(cell) if sanitize else cell}</td>'
271
+ )
272
+ html_table += "</tr>"
273
+
274
+ html_table += "</table>"
275
+ return html_table
276
+
277
+
278
+ @block("code")
279
+ class CodeBlock(EditorJsBlock):
280
+ def html(self, sanitize: bool = False) -> str:
281
+ code = self.data.get("code", "")
282
+ if sanitize:
283
+ code = _sanitize(code)
284
+ return f"""
285
+ <code class="ce-code__textarea cdx-input" data-empty="false">{code}</code>
286
+ """
287
+
288
+
289
+ @block("warning")
290
+ class WarningBlock(EditorJsBlock):
291
+ def html(self, sanitize: bool = False) -> str:
292
+ title = self.data.get("title", "")
293
+ message = self.data.get("message", "")
294
+
295
+ if sanitize:
296
+ title = _sanitize(title)
297
+ message = _sanitize(message)
298
+
299
+ return f"""
300
+ <div class="cdx-block cdx-warning">
301
+ <div class="cdx-input cdx-warning__title">{title}</div>
302
+ <div class="cdx-input cdx-warning__message">{message}</div>
303
+ </div>
304
+ """
305
+
306
+
307
+ @block("raw")
308
+ class RawBlock(EditorJsBlock):
309
+ def html(self, sanitize: bool = False) -> str:
310
+ html = self.data.get("html", "")
311
+ if sanitize:
312
+ html = _sanitize(html)
313
+ return html
@@ -0,0 +1,19 @@
1
+ __all__ = [
2
+ "EditorJsException",
3
+ "EditorJsParseError",
4
+ "EditorJSUnsupportedBlock",
5
+ ]
6
+
7
+
8
+ class EditorJsException(Exception):
9
+ """
10
+ Base exception
11
+ """
12
+
13
+
14
+ class EditorJsParseError(EditorJsException):
15
+ """Raised when a parse error occurs (example: the JSON data has invalid or malformed content)."""
16
+
17
+
18
+ class EditorJSUnsupportedBlock(EditorJsException):
19
+ """Raised when strict=True and using an unknown block type."""
@@ -0,0 +1,75 @@
1
+ import typing as t
2
+ import warnings
3
+ from dataclasses import dataclass
4
+
5
+ from .blocks import BLOCKS_MAP, EditorJsBlock
6
+ from .exceptions import EditorJsParseError, EditorJSUnsupportedBlock
7
+
8
+
9
+ @dataclass
10
+ class EditorJsParser:
11
+ """
12
+ An Editor.js parser.
13
+ """
14
+
15
+ content: dict
16
+ """The JSON data of Editor.js content."""
17
+
18
+ def __post_init__(self) -> None:
19
+ if not isinstance(self.content, dict):
20
+ raise EditorJsParseError(
21
+ f"Content must be `dict`, not {type(self.content).__name__}"
22
+ )
23
+
24
+ @staticmethod
25
+ def _get_block(data: dict, strict: bool = False) -> t.Optional[EditorJsBlock]:
26
+ """
27
+ Obtains block instance from block data.
28
+ """
29
+
30
+ _type = data.get("type", None)
31
+
32
+ if _type not in BLOCKS_MAP:
33
+ if strict:
34
+ raise EditorJSUnsupportedBlock(_type)
35
+ else:
36
+ warnings.warn(f"Unsupported block: {_type}", category=RuntimeWarning)
37
+ return None
38
+
39
+ return BLOCKS_MAP[_type](_data=data)
40
+
41
+ def blocks(self, strict: bool = False) -> list[EditorJsBlock]:
42
+ """
43
+ Obtains a list of all available blocks from the editor's JSON data.
44
+ """
45
+
46
+ all_blocks: list[EditorJsBlock] = []
47
+ blocks = self.content.get("blocks", [])
48
+
49
+ if not isinstance(blocks, list):
50
+ raise EditorJsParseError(
51
+ f"Blocks is not `list`, but `{type(blocks).__name__}`"
52
+ )
53
+
54
+ for block_data in blocks:
55
+ if block := self._get_block(data=block_data, strict=strict):
56
+ all_blocks.append(block)
57
+
58
+ return all_blocks
59
+
60
+ def __iter__(self) -> t.Iterator[EditorJsBlock]:
61
+ """Returns `iter(self.blocks())`"""
62
+
63
+ return iter(self.blocks())
64
+
65
+ def html(self, sanitize: bool = False, strict: bool = False) -> str:
66
+ """
67
+ Renders the editor's JSON content as HTML.
68
+
69
+ ### Parameters:
70
+ - `sanitize` - whether to also sanitize the blocks' texts/contents.
71
+ """
72
+
73
+ return "\n".join(
74
+ [block.html(sanitize=sanitize) for block in self.blocks(strict=strict)]
75
+ )