Package: draftjs-exporter
Draft.js exporterLibrary to convert rich text from Draft.js raw ContentState to HTML.It is developed alongside theDraftailrich text editor, forWagtail. Check out theonline demo, and ourintroductory blog post.WhyDraft.jsis a rich text editor framework forReact. Its approach is different from most rich text editors because it does not store data as HTML, but rather in its own representation called ContentState. This exporter is useful when the ContentState to HTML conversion has to be done in a Python ecosystem.The initial use case was to gain more control over the content managed by rich text editors in a Wagtail/Django site. If you want to read the full story, have a look at our blog post:Rethinking rich text pipelines with Draft.js.FeaturesThis project adheres toSemantic Versioning, andmeasures performanceandcode coverage. Code is checked withmypy.Extensive configuration of the generated HTML.Default, extensible block & inline style maps for common HTML elements.Convert line breaks to<br>elements.Define any attribute in the block map – custom class names for elements.React-like API to create custom components.Automatic conversion of entity data to HTML attributes (int & boolean to string, style object to style string).Nested lists (<li>elements go inside<ul>or<ol>, with multiple levels).Output inline styles as inline elements (<em>,<strong>, pick and choose, with any attribute).Overlapping inline style and entity ranges.Static type annotations.UsageDraft.js stores data in a JSON representation based on blocks, representing lines of content in the editor, annotated with entities and styles to represent rich text. For more information,this articlecovers the concepts further.Getting startedThis exporter takes the Draft.js ContentState data as input, and outputs HTML based on its configuration. To get started, install the package:pipinstalldraftjs_exporterWe support the following Python versions: 3.7, 3.8, 3.9, 3.10, 3.11. For legacy Python versions, find compatible releases in theCHANGELOG.In your code, create an exporter and use therendermethod to create HTML:fromdraftjs_exporter.domimportDOMfromdraftjs_exporter.htmlimportHTML# Configuration options are detailed below.config={}# Initialise the exporter.exporter=HTML(config)# Render a Draft.js `contentState`html=exporter.render({'entityMap':{},'blocks':[{'key':'6mgfh','text':'Hello, world!','type':'unstyled','depth':0,'inlineStyleRanges':[],'entityRanges':[]}]})print(html)You can also run an example by downloading this repository and then usingpython example.py, or by using ouronline Draft.js demo.ConfigurationThe exporter output is extensively configurable to cater for varied rich text requirements.# draftjs_exporter provides default configurations and predefined constants for reuse.fromdraftjs_exporter.constantsimportBLOCK_TYPES,ENTITY_TYPESfromdraftjs_exporter.defaultsimportBLOCK_MAP,STYLE_MAPfromdraftjs_exporter.domimportDOMconfig={# `block_map` is a mapping from Draft.js block types to a definition of their HTML representation.# Extend BLOCK_MAP to start with sane defaults, or make your own from scratch.'block_map':dict(BLOCK_MAP,**{# The most basic mapping format, block type to tag name.BLOCK_TYPES.HEADER_TWO:'h2',# Use a dict to define props on the block.BLOCK_TYPES.HEADER_THREE:{'element':'h3','props':{'class':'u-text-center'}},# Add a wrapper (and wrapper_props) to wrap adjacent blocks.BLOCK_TYPES.UNORDERED_LIST_ITEM:{'element':'li','wrapper':'ul','wrapper_props':{'class':'bullet-list'},},# Use a custom component for more flexibility (reading block data or depth).BLOCK_TYPES.BLOCKQUOTE:blockquote,BLOCK_TYPES.ORDERED_LIST_ITEM:{'element':list_item,'wrapper':ordered_list,},# Provide a fallback component (advanced).BLOCK_TYPES.FALLBACK:block_fallback}),# `style_map` defines the HTML representation of inline elements.# Extend STYLE_MAP to start with sane defaults, or make your own from scratch.'style_map':dict(STYLE_MAP,**{# Use the same mapping format as in the `block_map`.'KBD':'kbd',# The `style` prop can be defined as a dict, that will automatically be converted to a string.'HIGHLIGHT':{'element':'strong','props':{'style':{'textDecoration':'underline'}}},# Provide a fallback component (advanced).INLINE_STYLES.FALLBACK:style_fallback,}),'entity_decorators':{# Map entities to components so they can be rendered with their data.ENTITY_TYPES.IMAGE:image,ENTITY_TYPES.LINK:link# Lambdas work too.ENTITY_TYPES.HORIZONTAL_RULE:lambdaprops:DOM.create_element('hr'),# Discard those entities.ENTITY_TYPES.EMBED:None,# Provide a fallback component (advanced).ENTITY_TYPES.FALLBACK:entity_fallback,},'composite_decorators':[# Use composite decorators to replace text based on a regular expression.{'strategy':re.compile(r'\n'),'component':br,},{'strategy':re.compile(r'#\w+'),'component':hashtag,},{'strategy':LINKIFY_RE,'component':linkify,},],}Seeexamples.pyfor more details.Advanced usageCustom componentsTo generate arbitrary markup with dynamic data, the exporter comes with an API to create rendering components. This API mirrors React’screateElementAPI (what JSX compiles to).# All of the API is available from a single `DOM` namespacefromdraftjs_exporter.domimportDOM# Components are simple functions that take `props` as parameter and return DOM elements.defimage(props):# This component creates an image element, with the relevant attributes.returnDOM.create_element('img',{'src':props.get('src'),'width':props.get('width'),'height':props.get('height'),'alt':props.get('alt'),})defblockquote(props):# This component uses block data to render a blockquote.block_data=props['block']['data']# Here, we want to display the block's content so we pass the `children` prop as the last parameter.returnDOM.create_element('blockquote',{'cite':block_data.get('cite')},props['children'])defbutton(props):href=props.get('href','#')icon_name=props.get('icon',None)text=props.get('text','')returnDOM.create_element('a',{'class':'icon-text'ificon_nameelseNone,'href':href,},# There can be as many `children` as required.# It is also possible to reuse other components and render them instead of HTML tags.DOM.create_element(icon,{'name':icon_name})ificon_nameelseNone,DOM.create_element('span',{'class':'icon-text'},text)ificon_nameelsetext)Apart fromcreate_element, aparse_htmlmethod is also available. Use it to interface with other HTML generators, like template engines.Seeexamples.pyin the repository for more details.Fallback componentsWhen dealing with changes in the content schema, as part of ongoing development or migrations, some content can go stale.
To solve this, the exporter allows the definition of fallback components for blocks, styles, and entities.
This feature is only used for development at the moment, if you have a use case for this in production we would love to hear from you.
Please get in touch!Add the following to the exporter config,config={'block_map':dict(BLOCK_MAP,**{# Provide a fallback for block types.BLOCK_TYPES.FALLBACK:block_fallback}),}This fallback component can now control the exporter behavior when normal components are not found. Here is an example:defblock_fallback(props):type_=props['block']['type']iftype_=='example-discard':logging.warn(f'Missing config for "{type_}". Discarding block, keeping content.')# Directly return the block's children to keep its content.returnprops['children']eliftype_=='example-delete':logging.error(f'Missing config for "{type_}". Deleting block.')# Return None to not render anything, removing the whole block.returnNoneelse:logging.warn(f'Missing config for "{type_}". Using div instead.')# Provide a fallback.returnDOM.create_element('div',{},props['children'])Seeexamples.pyin the repository for more details.Alternative backing enginesBy default, the exporter uses a dependency-free engine calledstringto build the DOM tree. There are alternatives:html5lib(via BeautifulSoup)lxml.string_compat(A variant ofstringwith no backwards-incompatible changes since its first release).Thestringengine is the fastest, and does not have any dependencies. Its only drawback is that theparse_htmlmethod does not escape/sanitise HTML like that of other engines.Forhtml5lib, dopip install draftjs_exporter[html5lib].Forlxml, dopip install draftjs_exporter[lxml]. It also requireslibxml2andlibxsltto be available on your system.There are no additional dependencies forstring_compat.Then, use theengineattribute of the exporter config:config={# Specify which DOM backing engine to use.'engine':DOM.HTML5LIB,# Or for lxml:'engine':DOM.LXML,# Or to use the "maximum output stability" string_compat engine:'engine':DOM.STRING_COMPAT,}Custom backing enginesThe exporter supports using custom engines to generate its output via theDOMAPI. This can be useful to implement custom export formats, e.g.to Markdown (experimental).Here is an example implementation:fromdraftjs_exporterimportDOMEngineclassDOMListTree(DOMEngine):"""Element tree using nested lists."""@staticmethoddefcreate_tag(t,attr=None):return[t,attr,[]]@staticmethoddefappend_child(elt,child):elt[2].append(child)@staticmethoddefrender(elt):returneltexporter=HTML({# Use the dotted module syntax to point to the DOMEngine implementation.'engine':'myproject.example.DOMListTree'})Type annotationsThe exporter’s codebase uses static type annotations, checked with mypy. Reusable types are made available:fromdraftjs_exporter.domimportDOMfromdraftjs_exporter.typesimportElement,Props# Components are simple functions that take `props` as parameter and return DOM elements.defimage(props:Props)->Element:# This component creates an image element, with the relevant attributes.returnDOM.create_element('img',{'src':props.get('src'),'width':props.get('width'),'height':props.get('height'),'alt':props.get('alt'),})ContributingSee anything you like in here? Anything missing? We welcome all support, whether on bug reports, feature requests, code, design, reviews, tests, documentation, and more. Please have a look at ourcontribution guidelines.If you just want to set up the project on your own computer, the contribution guidelines also contain all of the setup commands.CreditsThis project is made possible by the work ofSpringload, a New Zealand digital agency. Thebeautifuldemo site is the work of@thibaudcolas.View the full list ofcontributors.MIT licensed.