Code Monkey home page Code Monkey logo

draftjs-to-html's Introduction

DraftJS TO HTML

A library for converting DraftJS Editor content to plain HTML.

This is draft to HTML library I wrote for one of my projects. I am open-sourcing it so that others can also be benefitted from my work.

Installation

npm install draftjs-to-html

Usage

import { convertToRaw } from 'draft-js';
import draftToHtml from 'draftjs-to-html';

const rawContentState = convertToRaw(editorState.getCurrentContent());

const markup = draftToHtml(
  rawContentState, 
  hashtagConfig, 
  directional, 
  customEntityTransform
);

The function parameters are:

  1. contentState: Its instance of RawDraftContentState

  2. hashConfig: Its configuration object for hashtag, its required only if hashtags are used. If the object is not defined hashtags will be output as simple text in the markdown.

    hashConfig = {
      trigger: '#',
      separator: ' ',
    }

    Here trigger is character that marks starting of hashtag (default '#') and separator is character that separates characters (default ' '). These fields in hastag object are optional.

  3. directional: Boolean, if directional is true text is aligned according to bidi algorithm. This is also optional.

  4. customEntityTransform: Its function to render custom defined entities by user, its also optional.

    editorState is instance of DraftJS EditorState.

Supported conversions

Following is the list of conversions it supports:

  1. Convert block types to corresponding HTML tags:

    Block Type HTML Tag
    1 header-one h1
    2 header-two h2
    3 header-three h3
    4 header-four h4
    5 header-five h5
    6 header-six h6
    7 unordered-list-item ul
    8 ordered-list-item ol
    9 blockquote blockquote
    10 code pre
    11 unstyled p

    It performs these additional changes to text of blocks:

    • replace blank space in beginning and end of block with  
    • replace \n with <br>
    • replace < with &lt;
    • replace > with &gt;
  2. Converts ordered and unordered list blocks with depths to nested structure of <ul>, <ol> and <li>.

  3. Converts inline styles BOLD, ITALIC, UNDERLINE, STRIKETHROUGH, CODE, SUPERSCRIPT, SUBSCRIPT to corresponding HTML tags: <strong>, <em>, <ins>, <code>, <sup>, <sub>.

  4. Converts inline styles color, background-color, font-size, font-family to a span tag with inline style details: <span style="color:xyz;font-size:xx">. (The inline styles in JSON object should start with strings color or font-size like color-red, color-green or fontsize-12, fontsize-20).

  5. Converts entity range of type link to anchor tag using entity data url for href, targetOption for target: <a href="url" target="_self">text</a>. Default target is _self.

  6. Converts entity range of type mention to anchor tag using entity data url for href and value for data-value, it also adds class to it: <a href="url" class="wysiwyg-mention" data-mention data-value="value">text</a>.

  7. Converts atomic entity image to image tag using entity data src for image source, and if present alt, alignment, height, width also: <img src="src" alt="alt_text" style="float: left, height: 50px; width: 50px"/>.

  8. Converts embedded links to iFrames, using width, height and src from entity data. <iframe width="width" height="height" src="src" frameBorder="0"></iframe>

  9. Converts hashtags to anchor tag: <a href="#tag" class="wysiwyg-hashtag">#tag</a>.

  10. customEntityTransform can be used for transformation of a custom entity block to html. If present its call to generate html for entity. It can take 2 parameter:

    1. entity ( object with { type, mutalibity, data})
    2. text text present in the block.
  11. Adding style property to block tag for block level styles like text-align: <p style="text-align: right">text</p>.

  12. RTL, if directional function parameter is true, generated blocks have property dir = "auto" thus they get aligned according to bidi algorithm.

License

MIT.

draftjs-to-html's People

Contributors

amwam avatar avdeev avatar blittle avatar chrisvxd avatar dakom avatar daxianyu avatar dependabot[bot] avatar houfio avatar jpuri avatar mikelp avatar mjgreen145 avatar nathanhoad avatar nickdima avatar tammomueller avatar teknologist avatar xurei avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

draftjs-to-html's Issues

Use of draftjs mention plugin

I tryied to use your code, but I use mention plugin.

Can you describe how I can render mention properly (with links)?

thanks

draftToHtml is not function

at the time of implementing the function I get the following error:

draftjs_to_html_1.default is not a function
TypeError: draftjs_to_html_1.default is not a function
at WysiwygCustom._this.getContentText (http://localhost:9001/0.b77eb44ab9d2dac8797c.hot-update.js:86:60)
at WysiwygCustom._this.onEditorStateChange (http://localhost:9001/0.b77eb44ab9d2dac8797c.hot-update.js:34:42)
at WysiwygCustom.webpackHotUpdate.1359.WysiwygCustom.componentDidMount (http://localhost:9001/0.b77eb44ab9d2dac8797c.hot-update.js:121:14)
at commitLifeCycles (http://localhost:9001/static/preview.bundle.js:45867:22)
at commitAllLifeCycles (http://localhost:9001/static/preview.bundle.js:46961:7)
at HTMLUnknownElement.callCallback (http://localhost:9001/static/preview.bundle.js:31719:14)
at Object.invokeGuardedCallbackDev (http://localhost:9001/static/preview.bundle.js:31757:16)
at invokeGuardedCallback (http://localhost:9001/static/preview.bundle.js:31806:29)
at commitRoot (http://localhost:9001/static/preview.bundle.js:47100:7)
at completeRoot (http://localhost:9001/static/preview.bundle.js:48115:34)

Change log or release history?

Is there any consolidated info on the changes between versions, a change log perhaps?

It would be really nice if the releases were tagged in github and had information about the changes since the last version. And/or there could be a CHANGELOG.md. It's difficult to upgrade if we have to read the diffs of every commit to see what changed!

Adding a new line in the editor

When adding a new line into the editor, it adds an empty <p></p> tag instead of <br/> tag is this expected behaviour.. If so why??

Thoughts on Deprecating this in favor of draft-convert

Hey @jpuri , thanks so much for all your hard work on this project!

It was my first go to when searching to a draft-js to html conversion library, while developing I can across a few limitations around your implementation. specifically around entity conversions.

I did fix this by using the draft-convert library which is much more robust.

Curious to hear your thoughts on deprecating this in favor of draft convert to keep everyone on the same page and others don't run into similar pitfalls?

React's dangerouslySetInnerHTML

Is it safe to use draftToHTML the content inside react using dangerouslySetInnerHTML without sanitizing? I'm assuming because there are only limited html tags this package supports to convert. Also how would I sanitize the draftjs content to be safe?
Sorry I asked this in stackoverflow but no real response yet.

Non-pixel font sizes aren't converted correctly

Relates to jpuri/html-to-draftjs#46

Per the CSS spec, font-size can take absolute and relative values, as well as global values, e.g:
font-size: medium;
font-size: larger;
font-size: inherit;

This library currently assumes all font sizes are in pixels, and therefore just adds 'px' to the end of the stored font-size.

Steps to reproduce:

  1. Go to https://jpuri.github.io/react-draft-wysiwyg/#/demo
  2. On the first demo (which shows you the outputted html), copy the text which is there, then paste.

Result:

image

The outputted html has font-size: medipx.

I am working on a fix for this and hope to get a PR open shortly.

Inline style does not get included in HTML

I use draftjs-color-picker version 1.0.2 and draftToHtml version 0.8.3 and this is my code:

const contentRaw = convertToRaw(this.state.editorState.getCurrentContent())
const contentHtml = draftToHtml(contentRaw)

contentRaw:

{
blocks: Array(1)
0: data: {}
depth: 0
entityRanges: []
inlineStyleRanges: Array(1)
0: {offset: 4, length: 4, style: "CUSTOM_COLOR_rgba(74, 144, 226, 1)"}
length: 1
__proto__: Array(0)
key: "2h4he"
text: "One blue color"
...

contentHtml:
<p>One blue color</p>

When I look at demo of https://jpuri.github.io/react-draft-wysiwyg/#/demo I can see that the same code produces styled HTML.

Why does it not work for me?

Wrong image alignment

Hi. Thank you for your projects.
I think image center/left/right align convertation doesn't work properly. A html output looks differently than in editor.

<p>Hey this <strong>editor</strong> rocks</p>
<img src="https://www.shareicon.net/data/128x128/2016/07/08/117367_logo_512x512.png" alt="undefined" style="float:none;height: auto;width: auto"/>
<p>bar</p>

image

differences between code and code-block

In the draftjs's document 'code-block' was rendered as block-level element and 'code' was as inline-level,but in your code, 'code' was mapped to block-level element . Maybe you should think to change it to adjust to the draftjs's document

customEntityTransform is not applied if entity is within bullet list

I bumped into this recently, because I wanted to override with customEntityTransform that every link included is opened into a new tab. Somehow it seems that customEntityTransform is not taken into account if entity is within a bullet list.

Is that intended? Id be more than happy to dive into this next week and do a pr, if there are any active maintainers.

method getStyleTagSectionMarkup(styleSection) calls addInlineStyleMarkup incorrectly

In Method getStyleTagSectionMarkup(styleSection) addInlineStyleMarkup is called with 3 parameters insted of 2

function getStyleTagSectionMarkup(styleSection) {
    var styles = styleSection.styles,
        text = styleSection.text;

    var content = getSectionText(text);
    forEach(styles, function (style, value) {
        content = addInlineStyleMarkup(style, content, value);
    });
    return content;
}
function addInlineStyleMarkup(style, content) {
    if (style === 'BOLD') {
        return '<strong>' + content + '</strong>';
    } else if (style === 'ITALIC') {
        return '<em>' + content + '</em>';
    } else if (style === 'UNDERLINE') {
        return '<ins>' + content + '</ins>';
    } else if (style === 'STRIKETHROUGH') {
        return '<del>' + content + '</del>';
    } else if (style === 'CODE') {
        return '<code>' + content + '</code>';
    } else if (style === 'SUPERSCRIPT') {
        return '<sup>' + content + '</sup>';
    } else if (style === 'SUBSCRIPT') {
        return '<sub>' + content + '</sub>';
    }
    return content;
}

End of content is excluded from most recent changes

Thank you @jpuri for all your work here.

In using your editor and changing to html, I noticed that part of the stylings is not being applied to all the content. I even tried it in storybook mode and was able to reproduce the error.

It appears that when an emoji is inserted, it will leave off the final character from the applied stylings.

For example:

๐Ÿค” What's wrong with lines with emojis?
becomes
<p>๐Ÿค” What's wrong with lines with<strong> emojis</strong>?</p>

The question mark was excluded from the bold styling

and
๐Ÿ˜๐Ÿ˜€ double trouble
becomes
<p><strong>๐Ÿ˜๐Ÿ˜€ double troub</strong>le</p>

Insert &nbsp; in whitespaces

Currently when I insert spaces in draftjs editor, draftToHtml(convertToRaw(editorState.getCurrentContent()))
does not convert whitespaces to nbsp when not at the end/start of a block.

How do I put nbsp; in the middle of paragraph tags as well?

Code blocks are stripped

Sadly, code block html is not showing up when using

draftToHtml(convertToRaw(editorContent.getCurrentContent()))

All I get is a blank where the code blocks were in the editor.

I confirmed that convertToRaw(editorContent.getCurrentContent()) functions as expected which leaves draftToHTML as the culprit

Using two Bullet point lists do not render correctly

If you have content as displayed in the convertToRaw of the editorState.

7: {key: "5qoqm", text: "NumberedList   ", type: "ordered-list-item", depth: 0, inlineStyleRanges: Array(0), โ€ฆ}
8: {key: "dn5n", text: "sub", type: "ordered-list-item", depth: 1, inlineStyleRanges: Array(0), โ€ฆ}
9: {key: "53r0c", text: "sub 2", type: "ordered-list-item", depth: 2, inlineStyleRanges: Array(0), โ€ฆ}
10: {key: "8kagr", text: "BulletList", type: "unordered-list-item", depth: 0, inlineStyleRanges: Array(0), โ€ฆ}
11: {key: "2u2p6", text: "sub", type: "unordered-list-item", depth: 1, inlineStyleRanges: Array(0), โ€ฆ}
12: {key: "cffgo", text: "sub 2", type: "unordered-list-item", depth: 2, inlineStyleRanges: Array(0), โ€ฆ}

Which looks like

1. NumberedList
   1. sub
      1. sub 2
* BulletList
   * sub
       * sub 2

The html produced is

<ol>
  <li>NumberedList</li>
</ol>
<ul>
  <li>BulletList</li>
  <ol>
    <li>sub</li>
  </ol>
  <ul>
    <li>sub</li>
    <ol>
      <li>sub 2</li>
    </ol>
  <ul>
  <li>sub 2</li>
</ul>
</ul>
</ul>

Which looks like

1. NumberedList
* BulletList
   1. sub
   * sub
      1. sub 2
       * sub 2

customEntityTransform not applied in list items because of wrong Param in getListMarkup

Hi,

there is a bug in the code in index.js:

const listHtml = getListMarkup( listBlocks, entityMap, hashtagConfig, customEntityTransform );

Should inlcude the directional paramater:

const listHtml = getListMarkup( listBlocks, entityMap, hashtagConfig, directional, customEntityTransform );

The missing paramater blocks entity rendering in list items.

Background color

Hello, i am trying to use background color with no success. The inline style in JSON object starts with string : backgroundcolor-some color. I have also tried : backgroundColor-some color, background-color-some color. Am i doing something wrong?

Thanks.

Custom markup transformation

@jpuri PR #2

We added functionality to transform custom entities to HTML. As you may recall one of the PRs we created for the editor allowed us to embed tweets, instagram posts, etc.

This is the counter part that allows the transformation of these entities into HTML.
This change is backwards compatible and will not break earlier versions of the package.

Also this PR will take care of PR #1 as you can define your own transformation for link entity.

Outputs empty string with no errors

When using draftToHtml on a valid raw state I only get an empty string. There are no errors or warning being raised, just an empty string returned.

Change default target option

How to change target option of anchor tag from "_self" to "_blank" and how to change css of anchor tag?
Page is not opening in new tab even when the checkbox "open link in a new tab" is checked

Not all inline styles are getting converted

Hi,

I tried to paste below html

<div style="color: red;border: 1px solid green">Sample text</div>

But it stripped away border color and allowed only color. Is there anyway we can edit full html without any restrictions?

<div style="color: red;">Sample text</div>

support for latex.

I am looking for latex support which seems to be missing. I have to write mathematical equations and there seems to be no way to write or show them. How will I be able to achieve it?

Images

How to get pure "< img src='...'>" object, without "figure" ?

draftToHtml crashes with empty line from state

An empty line inserted from the editor results in a crash of the application.

Example DraftJS content state:

{
    "blocks": [
      {
        "data": [
          
        ],
        "depth": 0,
        "entityRanges": [
          
        ],
        "inlineStyleRanges": [
          
        ],
        "key": "8r1pn",
        "text": "Header",
        "type": "header-two"
      },
      {
        "data": [
          
        ],
        "depth": 0,
        "entityRanges": [
          
        ],
        "inlineStyleRanges": [
          {
            "length": 3,
            "offset": 5,
            "style": "BOLD"
          }
        ],
        "key": "o7di",
        "text": "Test",
        "type": "unstyled"
      },
      {
        "data": [
          
        ],
        "depth": 0,
        "entityRanges": [
          
        ],
        "inlineStyleRanges": [
          
        ],
        "key": "fjqu1",
        "text": null,
        "type": "unstyled"
      }
    ],
    "entityMap": [
      
    ]
  }

draftToHtml function with this state yields this error:

Uncaught TypeError: Cannot read property 'length' of null
    at getSections (draftjs-to-html.js:158)
    at getBlockInnerMarkup (draftjs-to-html.js:569)
    at getBlockMarkup (draftjs-to-html.js:610)
    at draftjs-to-html.js:703
    at Array.forEach (<anonymous>)
    at draftToHtml (draftjs-to-html.js:692)
    at index.js:14
    at commitHookEffectListMount (react-dom.development.js:19764)
    at commitPassiveHookEffects (react-dom.development.js:19802)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at flushPassiveEffectsImpl (react-dom.development.js:22884)
    at unstable_runWithPriority (scheduler.development.js:653)
    at runWithPriority$1 (react-dom.development.js:11061)
    at flushPassiveEffects (react-dom.development.js:22851)
    at react-dom.development.js:22730
    at workLoop (scheduler.development.js:597)
    at flushWork (scheduler.development.js:552)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:164)

Embed breaks content

It seems that if you have an embed in the content it drops everything following it.
Looking at the DOM there isn't anything else following the iframe created for the embed.
Loading the same content in the editor it shows up correctly.

Readme Usage is not clear

The example usage on the Readme file is as follows:

`
import draftToHtml from 'draftjs-to-html';

const rawContentState = convertToRaw(editorState.getCurrentContent());
const markup = draftToHtml(contentState, directional, customEntityTransform);
`

Its not clear what the arguments contentState, directional, and customEntityTransform should be ? And how is the rawContentState supposed to be used to get the markup ?

Thank you,
Akhilesh

HTML tags stripped

Hi @jpuri first of all, thank you for all your great work on this suite of projects for the react-draft-wysiwyg editor. Everything is working great, the only problem I am running is that enclosing DIV tags are getting stripped out somewhere. Basically, I have a templating system that should include some Bootstrap classes and they are all getting stripped out (not sure if this happens in draftToHtml or htmlToDraft functions. I'm using both of these plugins to handle HTML in / HTML out. Can you tell me if there is a workaround for this? Here is some sample code (assume that the argument 'newContent' looks something like this):
const newContent = '

<iframe width="250" height="141" src="https://www.youtube.com/embed/E0tgKVOxihI" frameborder="0" allowfullscreen></iframe>
'

appendContent = (newContent) => {
const { editorState } = this.state
// const content = stateToHTML(editorState.getCurrentContent())
const content = draftToHtml(convertToRaw(editorState.getCurrentContent()))
console.log(newContent)
const newHTML = htmlToDraft(<div>${content}${newContent}</div>)
const state = ContentState.createFromBlockArray(newHTML.contentBlocks)
this.setState({
editorState: EditorState.createWithContent(state)
},
() => {
this.setState({ dialogOpen: false })
console.log(draftToHtml(convertToRaw(this.state.editorState.getCurrentContent())))
}
)
}

When I go to pull the content as HTML, all of the DIV tags are gone. Can you tell me if there is a work-around for this? Thanks, Steve

React, render html saved from draft-js

I'm learning React: totally newbie.

If I save in DB the HTML directly from draft.js (or it's variants always based on it) and then in a view page of my React SPA I retrieve HTML from DB through my API:

QUESTIONS:

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.