Skip to content

API reference

This reference is generated from the package's public API, so it always matches what draftjs_exporter exports. Everything documented here is importable from the package root:

from draftjs_exporter import HTML, DOM, BLOCK_TYPES

Public API and metadata of draftjs_exporter.

This module gathers metadata, core classes, default configuration maps, type aliases, and helpers so callers can import everything from draftjs_exporter directly.

Exporter = HTML module-attribute

Compatibility alias for the HTML exporter.

HTMLExporter = HTML module-attribute

Compatibility alias for the HTML exporter.

HTML_CONFIG = {'block_map': BLOCK_MAP, 'style_map': STYLE_MAP, 'engine': DOM.STRING} module-attribute

Default exporter configuration using the built-in maps and string engine.

MARKDOWN_CONFIG = {'block_map': BLOCK_MAP, 'style_map': STYLE_MAP, 'entity_decorators': ENTITY_DECORATORS, 'composite_decorators': COMPOSITE_DECORATORS, 'engine': ENGINE} module-attribute

md_code_element = md_make_code_element() module-attribute

md_code_wrapper = md_make_code_wrapper('```') module-attribute

md_horizontal_rule = md_make_horizontal_rule('---') module-attribute

md_ol = md_make_ol('.') module-attribute

md_ul = md_make_ul('-') module-attribute

EntityResolver = Callable[[str, str], 'EntityResolution | None'] module-attribute

Resolve a URL and its label into an entity, or return None to defer.

ENTITY_TYPES = Enum('LINK', 'DOCUMENT', 'IMAGE', 'EMBED', 'HORIZONTAL_RULE', 'FALLBACK') module-attribute

Draft.js entity categories.

INLINE_STYLES = Enum('BOLD', 'CODE', 'ITALIC', 'UNDERLINE', 'STRIKETHROUGH', 'SUPERSCRIPT', 'SUBSCRIPT', 'MARK', 'QUOTATION', 'SMALL', 'SAMPLE', 'INSERT', 'DELETE', 'KEYBOARD', 'FALLBACK') module-attribute

Draft.js inline style names.

BLOCK_MAP = {BLOCK_TYPES.UNSTYLED: 'p', BLOCK_TYPES.HEADER_ONE: 'h1', BLOCK_TYPES.HEADER_TWO: 'h2', BLOCK_TYPES.HEADER_THREE: 'h3', BLOCK_TYPES.HEADER_FOUR: 'h4', BLOCK_TYPES.HEADER_FIVE: 'h5', BLOCK_TYPES.HEADER_SIX: 'h6', BLOCK_TYPES.UNORDERED_LIST_ITEM: {'element': 'li', 'wrapper': 'ul'}, BLOCK_TYPES.ORDERED_LIST_ITEM: {'element': 'li', 'wrapper': 'ol'}, BLOCK_TYPES.BLOCKQUOTE: 'blockquote', BLOCK_TYPES.PRE: 'pre', BLOCK_TYPES.CODE: code_block, BLOCK_TYPES.ATOMIC: render_children} module-attribute

Default mapping from block types to renderable tags or components.

STYLE_MAP = {INLINE_STYLES.BOLD: 'strong', INLINE_STYLES.CODE: 'code', INLINE_STYLES.ITALIC: 'em', INLINE_STYLES.UNDERLINE: 'u', INLINE_STYLES.STRIKETHROUGH: 's', INLINE_STYLES.SUPERSCRIPT: 'sup', INLINE_STYLES.SUBSCRIPT: 'sub', INLINE_STYLES.MARK: 'mark', INLINE_STYLES.QUOTATION: 'q', INLINE_STYLES.SMALL: 'small', INLINE_STYLES.SAMPLE: 'samp', INLINE_STYLES.INSERT: 'ins', INLINE_STYLES.DELETE: 'del', INLINE_STYLES.KEYBOARD: 'kbd'} module-attribute

Default mapping from inline styles to HTML tags.

Component = Callable[[Props], Element] module-attribute

Render a component from props and return an element.

CompositeDecorators = list[Decorator] module-attribute

List composite decorators applied while rendering blocks.

ConfigMap = dict[str, RenderableConfig | RenderableType] module-attribute

Map string keys to renderable configurations or values.

Element = Any module-attribute

Engine-specific element produced by a renderable.

EntityKey = str module-attribute

Key used to look up an entity in the entity map.

EntityMap = dict[EntityKey, Entity] module-attribute

Map entity keys to their definitions.

Mutability = Literal['MUTABLE', 'IMMUTABLE', 'SEGMENTED'] module-attribute

Draft.js entity mutability setting.

Props = dict[str, Any] module-attribute

Dictionary of string attribute keys to arbitrary values.

RenderableType = Component | Tag | None module-attribute

A tag name, component function, or None for a fragment.

Tag = str module-attribute

HTML tag name.

HTML

Combine entity, wrapper, and style state to render Draft.js content.

This is the main entry point for converting a Draft.js content state into an HTML string.

__init__(config=None)

Initialize the exporter with the given configuration.

Parameters:

Name Type Description Default
config ExporterConfig | None

Exporter options. Missing values use the default block and style maps and the string DOM engine.

None
build_command_groups(block)

Group block modification commands by start index.

Each group is paired with the slice of text the commands apply to.

Parameters:

Name Type Description Default
block Block

The Draft.js block whose commands are grouped.

required

Returns:

Type Description
list[tuple[str, list[Command]]]

Tuples of (text slice, commands applied to the slice).

build_commands(block)

Build all manipulation commands for a block.

The returned commands include a start and stop text marker plus one command for each inline style and entity range.

Parameters:

Name Type Description Default
block Block

The Draft.js block to build commands from.

required

Returns:

Type Description
list[Command]

The ordered list of manipulation commands.

render(content_state=None)

Render the given Draft.js content state as HTML.

render_block(block, entity_map, wrapper_state, dom)

Render a single block to an element.

Parameters:

Name Type Description Default
block Block

The Draft.js block to render.

required
entity_map EntityMap

Map of entity keys to entity definitions.

required
wrapper_state WrapperState

Stateful wrapper that handles nesting of list items.

required
dom type[DOMEngine]

Active DOM engine used to create elements.

required

Returns:

Type Description
Element

The rendered block element.

ExporterConfig

Bases: TypedDict

Available options when configuring an HTML exporter.

ContentState

Bases: TypedDict

Top-level Draft.js content state passed to the exporter.

DOM

Provide a DOM-building API that abstracts the active engine.

HTML5LIB = 'draftjs_exporter.engines.html5lib.DOM_HTML5LIB' class-attribute instance-attribute

Identifier for the html5lib DOM engine.

LXML = 'draftjs_exporter.engines.lxml.DOM_LXML' class-attribute instance-attribute

Identifier for the lxml DOM engine.

MARKDOWN = 'draftjs_exporter.engines.markdown.DOMMarkdown' class-attribute instance-attribute

Identifier for the Markdown DOM engine.

STRING = 'draftjs_exporter.engines.string.DOMString' class-attribute instance-attribute

Identifier for the string DOM engine.

STRING_COMPAT = 'draftjs_exporter.engines.string_compat.DOMStringCompat' class-attribute instance-attribute

Identifier for the string compatibility DOM engine.

append_child(elt, child) classmethod

Append a child node to an element.

camel_to_dash(camel_cased_str) staticmethod

Convert a camelCase string to a dashed-case attribute name.

create_element(type_=None, props=None, *elt_children) classmethod

Create an element or document fragment using the current engine.

The signature mirrors React.createElement: a type, an optional props dictionary, and zero or more children.

Parameters:

Name Type Description Default
type_ RenderableType

The tag name, component, or None for a fragment.

None
props Props | None

Attributes and metadata to pass to the element.

None
*elt_children Element | None

Child nodes to append to the element.

()

Returns:

Type Description
Element

The constructed element.

engine(engine) staticmethod

Temporarily set the DOM engine for the current context.

parse_html(markup) classmethod

Parse an HTML string into an element using the current engine.

render(elt) classmethod

Render an element tree to its final HTML output.

render_debug(elt) classmethod

Render an element tree to a debug-friendly representation.

use(engine) classmethod

Select the DOM implementation for the current context.

DOMEngine

Parent class of all DOM implementations.

append_child(elt, child) staticmethod

Append the given child node to the children of elt.

Parameters:

Name Type Description Default
elt Element

The parent element.

required
child Element

The child element to append.

required

Returns:

Type Description
Any

The parent element, or the value returned by the underlying engine.

create_tag(type_, attr=None) staticmethod

Create and return a new element of the given type and attributes.

Parameters:

Name Type Description Default
type_ Tag

The tag name of the element.

required
attr Attr | None

A mapping of attribute names to values.

None

Returns:

Type Description
Any

The newly created element.

parse_html(markup) staticmethod

Parse arbitrary HTML markup into an element.

This method is used in component implementations only, and is not required for the exporter to operate.

Parameters:

Name Type Description Default
markup HTML

The HTML string to parse.

required

Returns:

Type Description
Element

The parsed element.

render(elt) staticmethod

Render the given element and its children to HTML.

Parameters:

Name Type Description Default
elt Element

The element to render.

required

Returns:

Type Description
HTML

The rendered HTML string.

render_debug(elt) staticmethod

Render the given element to HTML for debugging.

Used in the exporter's tests, this method is not required for the exporter to operate.

Parameters:

Name Type Description Default
elt Element

The element to render.

required

Returns:

Type Description
HTML

The rendered HTML string.

ExporterEntityException

Bases: ExporterException

Raised when entity state manipulation is invalid or an entity is missing.

MarkdownOptions

Bases: TypedDict

Options available when customizing Markdown renderer output.

MarkdownImporter

Import Markdown text as a Draft.js ContentState.

Combines a parser engine (Markdown to ContentState) with a filter (content policy on the result). The parser is referenced by dotted path so alternative engines can be swapped in.

__init__(config=None)

Initialize the importer with the given configuration.

Parameters:

Name Type Description Default
config ImporterConfig | None

Parser engine, parser options, and filter rules.

None
import_markdown(markdown)

Parse Markdown and apply filter rules.

Parameters:

Name Type Description Default
markdown str

The Markdown text to import.

required

Returns:

Type Description
ContentState

The parsed, filtered ContentState.

Raises:

Type Description
MarkdownParseError

If the input cannot be parsed.

ConfigException

If a filter callback returns an invalid value during filtering.

ImporterConfig

Bases: TypedDict

Configuration for the Markdown importer.

filter_rules instance-attribute

Rules applied to the parsed ContentState.

parser instance-attribute

Dotted path of the parser engine class. Defaults to the built-in parser.

parser_config instance-attribute

Options passed to the parser engine constructor.

MarkdownParser

Parse Markdown text into a Draft.js ContentState.

Supports the CommonMark core: paragraphs, ATX headings, blockquotes, fenced code, thematic breaks, lists, emphasis, code spans, links, images, and hard line breaks. Every input produces either a structurally valid ContentState or a MarkdownParseError.

__init__(config=None)

Initialize the parser with the given configuration.

Parameters:

Name Type Description Default
config ParserConfig | None

Feature toggles and entity resolvers. Missing keys use defaults that enable all constructs.

None
parse(markdown)

Parse Markdown source into a ContentState.

Parameters:

Name Type Description Default
markdown str

The Markdown text to parse.

required

Returns:

Type Description
ContentState

A structurally valid Draft.js ContentState.

Raises:

Type Description
TypeError

If markdown is not a string.

MarkdownParseError

If an entity resolver fails.

ParserConfig

Bases: TypedDict

Options controlling which Markdown constructs are recognized.

blockquote instance-attribute

Parse > blockquotes (default: True).

code_fenced instance-attribute

Parse fenced code blocks (default: True).

code_inline instance-attribute

Parse backtick code spans (default: True).

emphasis instance-attribute

Parse bold and italic delimiters (default: True).

headings instance-attribute

Parse ATX headings (default: True).

image_resolvers instance-attribute

Resolver chain for image URLs (default: empty, uses IMAGE with src/alt).

images instance-attribute

Parse ![alt](url) images (default: True).

inline_html_styles instance-attribute

Whitelist of HTML tags mapped to inline styles, e.g. {"sup": "SUPERSCRIPT"}.

line_breaks instance-attribute

Strip two-space hard break markers (default: True).

Resolver chain for link URLs (default: empty, uses LINK with the URL).

Parse [label](url) links (default: True).

ordered_list instance-attribute

Parse ordered lists (default: True).

thematic_break instance-attribute

Parse thematic breaks (default: True).

unordered_list instance-attribute

Parse unordered lists (default: True).

ContentStateFilter

Apply declarative rules to a ContentState.

Rules run in definition order per object. Objects without a matching rule are kept. The filter always produces a structurally valid ContentState: entity ranges and the entity map stay in sync, and list depths are re-normalized after removals.

__init__(rules=None)

Initialize the filter, validating rules eagerly.

Parameters:

Name Type Description Default
rules list[FilterRule] | None

The rules to apply, in order.

None

Raises:

Type Description
ConfigException

If a rule is malformed.

apply(content_state)

Apply all rules, returning a new ContentState.

Parameters:

Name Type Description Default
content_state ContentState

The ContentState to filter. Not mutated.

required

Returns:

Type Description
ContentState

The filtered ContentState.

FilterRule

Bases: TypedDict

A single filtering rule.

action instance-attribute

What to do with matching objects.

match instance-attribute

The block type, style name, or entity type to match.

type instance-attribute

Which kind of object the rule matches.

MarkdownParseError

Bases: ExporterException

Raised when Markdown input cannot be parsed.

Carries an optional 1-based line number pointing at the source of the failure.

__init__(message, line=None)

Initialize the error with a message and optional line number.

Parameters:

Name Type Description Default
message str

Human-readable description of the failure.

required
line int | None

1-based source line number, if known.

None

EntityResolution

Bases: TypedDict

How a link or image URL should be converted into a Draft.js entity.

data instance-attribute

The entity data payload.

mutability instance-attribute

The entity mutability. Defaults to MUTABLE when omitted.

type instance-attribute

The entity type, e.g. LINK, IMAGE, DOCUMENT, EMBED.

BLOCK_TYPES

Draft.js block types mapped to HTML elements.

Block

Bases: TypedDict

Single Draft.js block within a content state.

Decorator

Bases: TypedDict

Pattern and component used to decorate matching text.

Entity

Bases: TypedDict

Draft.js entity data referenced by entity ranges.

EntityRange

Bases: TypedDict

Range of text associated with a single entity.

InlineStyleRange

Bases: TypedDict

Range of text styled by a single inline style.

RenderableConfig

Bases: TypedDict

Configuration describing how to render a single renderable.

build_markdown_config(options=None)

Build a Markdown exporter config with configurable output characters.

All options fall back to CommonMark-compatible defaults when omitted. Set a fallback to None to disable it.

Parameters:

Name Type Description Default
options MarkdownOptions | None

Overrides for Markdown characters and fallback components.

None

Returns:

Type Description
ExporterConfig

A full exporter config ready for HTML.

md_block(children)

Create a block fragment followed by an empty line.

Parameters:

Name Type Description Default
children list[str | Element]

The strings and elements that form the block content.

required

Returns:

Type Description
Element

A fragment containing the children and a trailing blank line.

md_block_fallback(props)

Render an unknown block type as plain text.

Parameters:

Name Type Description Default
props Props

Render properties including the unknown block definition.

required

Returns:

Type Description
Element

The block's children without extra markup.

md_blockquote(props)

Render a blockquote paragraph, joining consecutive quote paragraphs.

Draft.js quotes are one block per paragraph, but a multi-paragraph quote is a single Markdown blockquote: consecutive blockquote blocks are separated by an empty quote line (>) rather than a blank line, which would end the quote.

Parameters:

Name Type Description Default
props Props

Render properties including the current block and all blocks.

required

Returns:

Type Description
Element

A blockquote paragraph element.

md_code_block_fence(content, fence_char)

Compute a code fence that cannot be broken by the content.

The fence is one character longer than the longest run of the fence character in the content, and at least three characters long.

Parameters:

Name Type Description Default
content str

The raw code block content.

required
fence_char str

The fence character (backtick or tilde).

required

Returns:

Type Description
str

The fence string.

md_code_span(props)

Render inline code as a code span.

The engine emits the content unescaped, with delimiters sized to the content's backtick runs.

Parameters:

Name Type Description Default
props Props

Render properties including children.

required

Returns:

Type Description
Element

A code_span element.

md_entity_fallback(props)

Render an unknown entity type as plain text.

Parameters:

Name Type Description Default
props Props

Render properties including the unknown entity definition.

required

Returns:

Type Description
Element

The entity's children without extra markup.

Escape a URL for use as an inline link destination inside ](…).

Backslash-escapes backslashes and parentheses (which would otherwise break out of the destination), and percent-encodes ASCII whitespace and control characters, which inline destinations may not contain. Missing destinations (None) are rendered as empty, so links and images without a URL produce […]() rather than an error. URL scheme validation is out of scope: it is the integrator's responsibility (see docs/SECURITY.md).

Parameters:

Name Type Description Default
url str | None

The URL to escape, or None when the destination is absent.

required

Returns:

Type Description
str

The escaped destination.

md_escape_text(text, at_line_start=False)

Escape Markdown metacharacters in user-controlled text.

Applies CommonMark backslash escapes. Line-start-sensitive characters are only escaped at the start of a line: when at_line_start is true for the first line, and after every embedded line ending. All CommonMark line endings (\n, \r\n, and lone \r) count as line starts, and the original endings are preserved in the output.

Parameters:

Name Type Description Default
text str

The user-controlled text to escape. May contain line endings.

required
at_line_start bool

Whether the first character of text begins a line.

False

Returns:

Type Description
str

The escaped text, safe to emit into Markdown output.

md_image(props)

Render an image as a Markdown image reference.

Missing or None src renders an image with an empty destination (![alt]()) rather than raising an error.

Parameters:

Name Type Description Default
props Props

Render properties including alt and src.

required

Returns:

Type Description
Element

A block-level image element.

md_inline(children)

Create an inline fragment for inline formatting such as bold, links, and code.

Parameters:

Name Type Description Default
children list[str | Element]

The strings and elements to group inline.

required

Returns:

Type Description
Element

A fragment containing the children without extra whitespace.

md_inline_style(mark)

Create an inline style component that wraps text in the given mark.

Whitespace at the edges of the styled text is moved outside the marks: a style spanning a link is rendered per text segment, so an edge space would otherwise sit inside the delimiters (**bold **), where it is not valid emphasis. Styled text that is only whitespace renders without the marks, which would otherwise be empty.

Parameters:

Name Type Description Default
mark str

The delimiter to place before and after the styled text.

required

Returns:

Type Description
Component

A component that renders the marked inline style.

md_line_break(props)

Render a hard line break as Markdown syntax.

Headings are single-line Markdown constructs, so a hard break in a heading degrades to a plain space. Code blocks are passed through unmodified: their newlines already belong to the fenced output.

Parameters:

Name Type Description Default
props Props

Render properties including the current block.

required

Returns:

Type Description
Element

An inline element to insert where the line break occurs.

Render a link as a Markdown inline reference.

Whitespace at the start or end of the link text is moved outside the brackets: a link with the text " spaced " renders as " [spaced](url) " rather than "[ spaced ](url)".

Missing or None url renders a link with an empty destination ([children]()) rather than raising an error.

Parameters:

Name Type Description Default
props Props

Render properties including children and url.

required

Returns:

Type Description
Element

An inline link element.

Create an element holding a link or image URL for ](…).

Parameters:

Name Type Description Default
url str | None

The URL to escape and emit, or None when the destination is absent.

required

Returns:

Type Description
Element

An element rendering the escaped URL without further escaping.

md_list_wrapper(props)

Render a list wrapper as an empty inline fragment.

Markdown lists are built from individual items, so no extra wrapper markup is required.

Parameters:

Name Type Description Default
props Props

Render properties passed by the engine.

required

Returns:

Type Description
Element

An empty fragment that lets list items sit next to each other.

md_make_code_element()

Create a code-block line component.

Each Draft.js code block contributes one line to the shared code_block node created by the wrapper.

Returns:

Type Description
Component

A component that renders one line of code block content.

md_make_code_wrapper(fence)

Create a code-block wrapper component using the given fence.

Parameters:

Name Type Description Default
fence str

The fence delimiter; its first character sizes the rendered fence (``` or ~~~).

required

Returns:

Type Description
Component

A component that creates the code_block node holding all lines.

md_make_horizontal_rule(marker)

Create a horizontal rule component using the given marker.

Parameters:

Name Type Description Default
marker str

The literal marker characters to render.

required

Returns:

Type Description
Component

A component that renders a horizontal rule.

md_make_list_item(marker, delimiter)

Create a list item component with nesting indentation and numbering.

A block with no usable key renders as plain text, because the exporter creates such blocks for the wrapper nodes that nest lists, and those must not produce a list item of their own.

Both values also measure the content column of ancestors, whichever list type they belong to, so a component configured for one list type still needs the other type's value.

Parameters:

Name Type Description Default
marker str

The unordered list marker, without its trailing space.

required
delimiter str

The ordered list delimiter placed after the item number.

required

Returns:

Type Description
Component

A component that renders one list item.

md_make_ol(delimiter)

Create an ordered list item component using the given delimiter.

The unordered marker is only used to measure the content column of unordered ancestors, so the default one is enough here.

Parameters:

Name Type Description Default
delimiter str

The delimiter to place after the item number.

required

Returns:

Type Description
Component

A component that renders one ordered list item.

md_make_ul(marker)

Create an unordered list item component using the given marker.

The ordered delimiter is only used to measure the content column of ordered ancestors, so the default one is enough here.

Parameters:

Name Type Description Default
marker str

The marker character to use for each list item.

required

Returns:

Type Description
Component

A component that renders one unordered list item.

md_mark_safe(markup, block_prefix=False)

Create an element holding structural Markdown syntax.

The Markdown engine renders mark_safe markup verbatim, without the escaping applied to plain text children. Every piece of structural syntax emitted by Markdown components must be wrapped with this helper.

Parameters:

Name Type Description Default
markup str

The structural Markdown to emit (markers, fences, spacing).

required
block_prefix bool

Whether text following this markup can start a nested block. True for list markers, list indentation, and blockquote "> " prefixes; false for heading prefixes and inline marks.

False

Returns:

Type Description
Element

An element the Markdown engine renders without escaping.

md_prefixed_block(prefix, block_prefix=False)

Create a block component that prefixes its children with the given string.

Parameters:

Name Type Description Default
prefix str

The literal prefix to insert before the block's children.

required
block_prefix bool

Whether children can start a nested block after the prefix (true for blockquotes, false for headings).

False

Returns:

Type Description
Component

A component that renders the prefixed block.

md_style_fallback(props)

Render an unknown inline style as plain text.

Parameters:

Name Type Description Default
props Props

Render properties including the unknown inline style range.

required

Returns:

Type Description
Element

The styled children without extra markup.

scheme_resolver(scheme, type_map, coerce=None, label_key=None, mutability='MUTABLE')

Build a resolver for internal URLs like scheme://kind?key=value.

The URL host selects the entity type via type_map. Query string parameters become entity data, optionally converted per key via coerce. When a query key repeats, the last value wins (standard urllib dict semantics). When label_key is set, a non-empty Markdown label fills that data key if the query string did not provide it.

Parameters:

Name Type Description Default
scheme str

The URL scheme to match, e.g. "wagtail".

required
type_map dict[str, str]

Mapping of URL host to entity type.

required
coerce dict[str, Callable[[str], Any]] | None

Optional per-key converters for query string values.

None
label_key str | None

Optional data key filled from the Markdown label.

None
mutability Mutability

Mutability for produced resolutions.

'MUTABLE'

Returns:

Type Description
EntityResolver

A resolver that defers (returns None) for non-matching URLs.

code_block(props)

Render a code block inside a pre > code element tree.

render_children(props)

Return the children of a component without wrapping markup.