Skip to content

Instantly share code, notes, and snippets.

@shon
Last active January 16, 2020 12:09
Show Gist options
  • Save shon/102b3c628baa7b39657230361424d178 to your computer and use it in GitHub Desktop.
Save shon/102b3c628baa7b39657230361424d178 to your computer and use it in GitHub Desktop.
TiptapY (Object Oriented) Approach
import json
from dataclasses import dataclass, field
from typing import List
from inspect import isclass
renderers = {}
@dataclass
class BaseNode:
type = 'prose-mirror_content-type'
def render(self, in_data: field()):
out = self.inner_render(in_data)
if self.wrap_tag:
return f'<{self.wrap_tag}>{out}</{self.wrap_tag}>'
return out
def inner_render(self, node):
return node['content']
class BaseContainer(BaseNode):
wrap_tag = None
def inner_render(self, nodes: List):
out = ''
for node in nodes['content']:
node_type = node.get('type')
print(node_type)
renderer = renderers.get(node_type)
if renderer:
out += renderer.render(node)
return out
class Text(BaseNode):
type = 'text'
wrap_tag = 'span'
def inner_render(self, node):
text = node['text']
marks = node.get('marks')
if marks:
for mark in marks:
typ = mark.get('type')
if typ == 'bold':
text = f'<strong> {text} </strong>'
if typ == 'italic':
text = f'<i> {text} </i>'
return text
class Paragraph(BaseContainer):
type = 'paragraph'
wrap_tag = 'p'
class ListItem(BaseContainer):
type = 'list_item'
wrap_tag = 'li'
class BulletList(BaseContainer):
type = 'bullet_list'
wrap_tag = 'ul'
class Doc(BaseContainer):
type = 'doc'
for o in tuple(locals().values()):
if isclass(o) and issubclass(o, BaseNode):
renderers[o.type] = o()
def convert_any(in_data):
typ = in_data.get('type')
renderer = renderers.get(typ)
return renderer.render(in_data)
def to_html(s):
in_data = json.loads(s)
return convert_any(in_data)
def test():
s = open('tests/data.json').read()
out = to_html(s)
print(out)
if __name__ == '__main__':
test()
@gauravr
Copy link

gauravr commented Jan 16, 2020

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment