draftjs-to-html

repository·master·Indexed 43 days ago

https://github.com/jpuri/draftjs-to-html

A utility library version 0.9.1 for converting DraftJS Editor content (RawDraftContentState) into semantic HTML markup. It supports block types, inline styles, and entities such as links, mentions, images, and embedded links. Features include a customEntityTransform function for bespoke entity rendering, hashtag configuration via hashConfig, and RTL/Bidi support through a directional flag.

Tokens
1.7K
Snippets
5
Records
8
Agent score
6%

What's inside draftjs-to-html

  1. Configure hashtag rendering with hashConfig

    master

    If you want hashtags to be rendered as specific HTML elements rather than plain text, provide a hashConfig object. This object defines the trigger character and the separator.

    hashConfig = {
      trigger: '#',
      separator: ' ',
    }
  2. Implement custom entity rendering with customEntityTransform

    master

    To handle custom DraftJS entities, provide a customEntityTransform function. This function is called to generate HTML for specific entities and allows you to define how your custom data is mapped to HTML tags.

    The function signature is: customEntityTransform(entity, text)

    Where entity is an object containing:

    • type
    • mutability
    • data
  3. Convert DraftJS content to HTML with draftToHtml()

    master

    Use the draftToHtml function to transform a RawDraftContentState into an HTML string.

    Function Signature: draftToHtml(contentState, hashConfig, directional, customEntityTransform)

    Parameters:

    1. contentState (Required): An instance of RawDraftContentState (typically obtained via convertToRaw(editorState.getCurrentContent())).
    2. hashConfig (Optional): Configuration for hashtag rendering. If omitted, hashtags are output as simple text.
      • trigger: The character marking the start of a hashtag (default: '#').
      • separator: The character separating hashtag characters (default: ' ').
    3. directional (Optional): A boolean. If true, text is aligned according to the bidi algorithm by adding dir="auto" to generated blocks.
    4. customEntityTransform (Optional): A function used to render custom defined entities. It receives two arguments:
      • entity: An object containing { type, mutability, data }.
      • text: The text present in the block.
    import { convertToRaw } from 'draft-js';
    import draftToHtml from 'draftjs-to-html';
    
    const rawContentState = convertToRaw(editorState.getCurrentContent());
    
    const markup = draftToHtml(
      rawContentState, 
      hashtagConfig, 
      directional, 
      customEntityTransform
    );
  4. Configure hashtag detection with hashtagConfig

    master

    You can enable hashtag detection by passing a hashtagConfig object to draftToHtml. This allows the converter to identify hashtags within text blocks and wrap them in an anchor tag with the class wysiwyg-hashtag.

    Config Keys:

    • trigger (string): The character(s) that trigger a hashtag (defaults to '#').
    • separator (string): The character used to identify the start of a hashtag (defaults to ' ').
    const hashtagConfig = {
      trigger: '#',
      separator: ' '
    };
    
    const html = draftToHtml(editorContent, hashtagConfig);
  5. Supported HTML conversions and mappings

    master

    The library supports a wide range of DraftJS to HTML mappings:

    Block Types

    Block TypeHTML Tag
    header-one<h1>
    header-two<h2>
    header-three<h3>
    header-four<h4>
    header-five<h5>
    header-six<h6>
    unordered-list-item<ul> (nested via <li>)
    ordered-list-item<ol> (nested via <li>)
    blockquote<blockquote>
    code<pre>
    unstyled<p>

    Inline Styles

    • Standard Styles: BOLD $\rightarrow$ <strong>, ITALIC $\rightarrow$ <em>, UNDERLINE $\rightarrow$ <ins>, STRIKETHROUGH $\rightarrow$ (not explicitly mapped in table, but part of list), CODE $\rightarrow$ <code>, SUPERSCRIPT $\rightarrow$ <sup>, SUBSCRIPT $\rightarrow$ <sub>.
    • Color/Font Styles: Styles like color-red, color-green, or fontsize-12 are converted to a <span> with inline styles: <span style="color:xyz;font-size:xx">.

    Entities

    • Link: <a href="url" target="_self">text</a> (target defaults to _self).
    • Mention: <a href="url" class="wysiwyg-mention" data-mention data-value="value">text</a>.
    • Image (Atomic): <img src="src" alt="alt_text" style="float: left, height: 50px; width: 50px"/> (uses src, alt, alignment, height, and width from entity data).
    • Embedded Links: Uses <iframe> with width, height, and src from entity data.
    • Hashtags: <a href="#tag" class="wysiwyg-hashtag">#tag</a>.

    Additional Features

    • Text Sanitization: Replaces leading/trailing whitespace with &nbsp;, \n with <br>, < with &lt;, and > with &gt;.
    • Block Styles: Supports block-level styles like text-align (e.g., <p style="text-align: right">).
    • RTL/Bidi Support: If directional is true, blocks receive dir="auto".
  6. Customize entity rendering with customEntityTransform

    master

    To control how specific DraftJS entities are rendered in HTML, provide a customEntityTransform function as the fourth argument to draftToHtml.

    This function is called for each entity. If the function returns a non-empty string, that string is used as the HTML markup for the entity. If it returns nothing (or an empty string), the library falls back to its default entity rendering logic.

    Callback Signature: customEntityTransform(entity, text)

    • entity: The entity object from the entityMap.
    • text: The text content associated with the entity.
    const customEntityTransform = (entity, text) => {
      if (entity.type === 'MY_CUSTOM_ENTITY') {
        return `<span class="custom">${text}</span>`;
      }
      return null; // Fallback to default
    };
    
    const html = draftToHtml(editorContent, null, false, customEntityTransform);
  7. Default entity rendering behavior

    master

    If no customEntityTransform is provided, the library handles several common entity types automatically:

    Entity TypeHTML Output
    MENTION<a href="{url}" class="wysiwyg-mention" data-mention data-value="{value}">{text}</a>
    LINK<a href="{url}" target="{targetOption}">{text}</a> (target defaults to _self)
    IMAGE<div style="text-align:{alignment}"><img src="{src}" alt="{alt}" style="height: {height};width: {width}"/></div> (or a direct <img> if no alignment is provided)
    EMBEDDED_LINK<iframe width="{width}" height="{height}" src="{src}" frameBorder="0"></iframe>