edwh-editorjs 1.1.0__py3-none-any.whl → 2.0.0__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.
- editorjs/__about__.py +1 -0
- editorjs/__init__.py +5 -0
- editorjs/blocks.py +670 -0
- editorjs/core.py +119 -0
- editorjs/exceptions.py +3 -0
- editorjs/helpers.py +5 -0
- editorjs/types.py +43 -0
- edwh_editorjs-2.0.0.dist-info/METADATA +28 -0
- edwh_editorjs-2.0.0.dist-info/RECORD +11 -0
- {edwh_editorjs-1.1.0.dist-info → edwh_editorjs-2.0.0.dist-info}/licenses/LICENSE +1 -0
- edwh_editorjs-1.1.0.dist-info/METADATA +0 -104
- edwh_editorjs-1.1.0.dist-info/RECORD +0 -9
- pyeditorjs/__about__.py +0 -1
- pyeditorjs/__init__.py +0 -30
- pyeditorjs/blocks.py +0 -313
- pyeditorjs/exceptions.py +0 -19
- pyeditorjs/parser.py +0 -75
- {edwh_editorjs-1.1.0.dist-info → edwh_editorjs-2.0.0.dist-info}/WHEEL +0 -0
editorjs/core.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import typing as t
|
|
3
|
+
|
|
4
|
+
import markdown2
|
|
5
|
+
import mdast
|
|
6
|
+
from typing_extensions import Self
|
|
7
|
+
|
|
8
|
+
from .blocks import BLOCKS
|
|
9
|
+
from .helpers import unix_timestamp
|
|
10
|
+
from .types import MDRootNode
|
|
11
|
+
|
|
12
|
+
EDITORJS_VERSION = "2.30.6"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class EditorJS:
|
|
16
|
+
# internal representation is mdast, because we can convert to other types
|
|
17
|
+
_mdast: MDRootNode
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
_mdast: str | dict,
|
|
22
|
+
extras: list = ("task_list", "fenced-code-blocks", "tables", "editorjs"),
|
|
23
|
+
):
|
|
24
|
+
if not isinstance(_mdast, str | dict):
|
|
25
|
+
raise TypeError("Only `str` or `dict` is supported!")
|
|
26
|
+
|
|
27
|
+
self._mdast = t.cast(
|
|
28
|
+
MDRootNode, json.loads(_mdast) if isinstance(_mdast, str) else _mdast
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
self._md = markdown2.Markdown(extras=extras) # todo: striketrough, ?
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def from_json(cls, data: str | dict) -> Self:
|
|
35
|
+
"""
|
|
36
|
+
Load from EditorJS JSON Blocks
|
|
37
|
+
"""
|
|
38
|
+
data = data if isinstance(data, dict) else json.loads(data)
|
|
39
|
+
markdown_items = []
|
|
40
|
+
for child in data["blocks"]:
|
|
41
|
+
_type = child["type"]
|
|
42
|
+
if not (block := BLOCKS.get(_type)):
|
|
43
|
+
raise TypeError(f"Unsupported block type `{_type}`")
|
|
44
|
+
|
|
45
|
+
markdown_items.append(block.to_markdown(child.get("data", {})))
|
|
46
|
+
|
|
47
|
+
markdown = "".join(markdown_items)
|
|
48
|
+
return cls.from_markdown(markdown)
|
|
49
|
+
|
|
50
|
+
@classmethod
|
|
51
|
+
def from_markdown(cls, data: str) -> Self:
|
|
52
|
+
"""
|
|
53
|
+
Load from markdown string
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
return cls(mdast.md_to_json(data))
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def from_mdast(cls, data: str | dict) -> Self:
|
|
60
|
+
"""
|
|
61
|
+
Existing mdast representation
|
|
62
|
+
"""
|
|
63
|
+
return cls(data)
|
|
64
|
+
|
|
65
|
+
def to_json(self) -> str:
|
|
66
|
+
"""
|
|
67
|
+
Export EditorJS JSON Blocks
|
|
68
|
+
"""
|
|
69
|
+
# logic based on https://github.com/carrara88/editorjs-md-parser/blob/main/src/MarkdownImporter.js
|
|
70
|
+
blocks = []
|
|
71
|
+
for child in self._mdast["children"]:
|
|
72
|
+
_type = child["type"]
|
|
73
|
+
if not (block := BLOCKS.get(_type)):
|
|
74
|
+
raise TypeError(f"Unsupported block type `{_type}`")
|
|
75
|
+
|
|
76
|
+
blocks.extend(block.to_json(child))
|
|
77
|
+
|
|
78
|
+
data = {"time": unix_timestamp(), "blocks": blocks, "version": EDITORJS_VERSION}
|
|
79
|
+
|
|
80
|
+
return json.dumps(data)
|
|
81
|
+
|
|
82
|
+
def to_markdown(self) -> str:
|
|
83
|
+
"""
|
|
84
|
+
Export Markdown string
|
|
85
|
+
"""
|
|
86
|
+
md = mdast.json_to_md(self.to_mdast())
|
|
87
|
+
# idk why this happens:
|
|
88
|
+
md = md.replace(r"\[ ]", "[ ]")
|
|
89
|
+
md = md.replace(r"\[x]", "[x]")
|
|
90
|
+
return md
|
|
91
|
+
|
|
92
|
+
def to_mdast(self) -> str:
|
|
93
|
+
"""
|
|
94
|
+
Export mdast representation
|
|
95
|
+
"""
|
|
96
|
+
return json.dumps(self._mdast)
|
|
97
|
+
|
|
98
|
+
def to_html(self) -> str:
|
|
99
|
+
"""
|
|
100
|
+
Export HTML string
|
|
101
|
+
"""
|
|
102
|
+
md = self.to_markdown()
|
|
103
|
+
# todo: deal with custom elements like linktool, attaches
|
|
104
|
+
return self._md.convert(md)
|
|
105
|
+
|
|
106
|
+
def __repr__(self):
|
|
107
|
+
md = self.to_markdown()
|
|
108
|
+
md = md.replace("\n", "\\n")
|
|
109
|
+
return f"EditorJS({md})"
|
|
110
|
+
|
|
111
|
+
def __str__(self):
|
|
112
|
+
return self.to_markdown()
|
|
113
|
+
|
|
114
|
+
# def __eq__(self, other: Self) -> bool:
|
|
115
|
+
# a = self.to_markdown()
|
|
116
|
+
# b = other.to_markdown()
|
|
117
|
+
#
|
|
118
|
+
# remove = string.punctuation + string.whitespace
|
|
119
|
+
# return a.translate(remove) == b.translate(remove)
|
editorjs/exceptions.py
ADDED
editorjs/helpers.py
ADDED
editorjs/types.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import typing as t
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class MDPosition(t.TypedDict):
|
|
5
|
+
line: int
|
|
6
|
+
column: int
|
|
7
|
+
offset: int
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class MDPositionRange(t.TypedDict):
|
|
11
|
+
start: MDPosition
|
|
12
|
+
end: MDPosition
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MDChildNode(t.TypedDict, total=False):
|
|
16
|
+
type: str # General identifier for node types
|
|
17
|
+
children: list["MDChildNode"] # Recursive children of any node type
|
|
18
|
+
position: MDPositionRange
|
|
19
|
+
value: str # Optional, for nodes like text that hold a value
|
|
20
|
+
depth: int # Optional, for nodes like headings that have a depth
|
|
21
|
+
url: t.NotRequired[str]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class MDRootNode(t.TypedDict):
|
|
25
|
+
type: t.Literal["root"] # Constrains to 'root' for the root node
|
|
26
|
+
children: list[MDChildNode] # Allows any ChildNode type in children
|
|
27
|
+
position: MDPositionRange
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class EditorChildData(t.TypedDict, total=False):
|
|
31
|
+
text: str
|
|
32
|
+
items: list["EditorChildNode"]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class EditorChildNode(t.TypedDict):
|
|
36
|
+
type: str
|
|
37
|
+
data: EditorChildData
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class EditorRootNode(t.TypedDict):
|
|
41
|
+
time: int
|
|
42
|
+
blocks: list[EditorChildNode]
|
|
43
|
+
version: str
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: edwh-editorjs
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: EditorJS.py
|
|
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: markdown2
|
|
19
|
+
Requires-Dist: mdast
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: edwh; extra == 'dev'
|
|
22
|
+
Requires-Dist: hatch; extra == 'dev'
|
|
23
|
+
Requires-Dist: su6[all]; extra == 'dev'
|
|
24
|
+
Requires-Dist: types-bleach; extra == 'dev'
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# edwh-editorjs
|
|
28
|
+
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
editorjs/__about__.py,sha256=_7OlQdbVkK4jad0CLdpI0grT-zEAb-qgFmH5mFzDXiA,22
|
|
2
|
+
editorjs/__init__.py,sha256=-OHUf7ZXfkbdFB1r85eIjpHRfql-GCNUCKuBEdEt2Rc,58
|
|
3
|
+
editorjs/blocks.py,sha256=CTZPKIxjRQy1R1LPrqpB9NTvhSeSjekcMls6QAPdDoI,21664
|
|
4
|
+
editorjs/core.py,sha256=CdZnprX-vkjFJATxPfG1acDqGKkHa3mDfbMEeXiR6eI,3331
|
|
5
|
+
editorjs/exceptions.py,sha256=TyfHvk2Z5RbKxTDK7lrjgwAgVgInXIuDW63eO5jzVFw,106
|
|
6
|
+
editorjs/helpers.py,sha256=q861o5liNibMTp-Ozay17taF7CTNsRe901lYhhxdwHg,73
|
|
7
|
+
editorjs/types.py,sha256=W7IZWMWgzJaQulybIt0Gx5N63rVj4mEy73VJWo4VAQA,1029
|
|
8
|
+
edwh_editorjs-2.0.0.dist-info/METADATA,sha256=WnNAx-XckoOeSuXbNdJQHs2zto0xSeN1g3yPXXZ8T34,1007
|
|
9
|
+
edwh_editorjs-2.0.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
|
|
10
|
+
edwh_editorjs-2.0.0.dist-info/licenses/LICENSE,sha256=zzllbk0pvnmgzk31iq8Zkg0GkA8vVx_Zc3OHjVlTjxo,1101
|
|
11
|
+
edwh_editorjs-2.0.0.dist-info/RECORD,,
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.3
|
|
2
|
-
Name: edwh-editorjs
|
|
3
|
-
Version: 1.1.0
|
|
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!
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
pyeditorjs/__about__.py,sha256=LGVQyDsWifdACo7qztwb8RWWHds1E7uQ-ZqD8SAjyw4,22
|
|
2
|
-
pyeditorjs/__init__.py,sha256=63UoNCWJo6NuPXXYnANQE3SKm1PQu2ggs89KCXSq-44,807
|
|
3
|
-
pyeditorjs/blocks.py,sha256=4A8dXbh_oUKCctOHtMV6BrR7-UpyqFREPvwPEe_6vUo,8304
|
|
4
|
-
pyeditorjs/exceptions.py,sha256=Uni8r3FwJ-6xQIdSmBsHLs_htWLHD0Arp1KJEvjGU1U,439
|
|
5
|
-
pyeditorjs/parser.py,sha256=6DCqqi-FuXDFxn9xb-dgQ19alvVu7Pjx6x3rTAx9IsI,2154
|
|
6
|
-
edwh_editorjs-1.1.0.dist-info/METADATA,sha256=Aq3-6WNcqqhbufFvnigNO-txrmV_6OppGmliWoK7tf4,3519
|
|
7
|
-
edwh_editorjs-1.1.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
|
|
8
|
-
edwh_editorjs-1.1.0.dist-info/licenses/LICENSE,sha256=bY9MhHLeuW8w1aAl-i1O1uSNP5IMOGaL6AWvHcdnt0k,1062
|
|
9
|
-
edwh_editorjs-1.1.0.dist-info/RECORD,,
|
pyeditorjs/__about__.py
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "1.1.0"
|
pyeditorjs/__init__.py
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
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]
|
pyeditorjs/blocks.py
DELETED
|
@@ -1,313 +0,0 @@
|
|
|
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
|