betancourtl / draft-js-custom-styles

Create custom inline styles for draft-js in a sane way
MIT License
34 stars 17 forks source link

Instantiate EditorState from HTML #2

Open rpellerin opened 6 years ago

rpellerin commented 6 years ago

Hi, Thanks for developing such a useful library! My question might seem dumb but I can't figure how to do it... How can I generate an EditorState out of exported HTML, which preserves inline styles?

I use the following chunk of code to get HTML from an editorState, which works perfectly:

import { stateToHTML } from 'draft-js-export-html'

const inlineStyles = exporter(editorState)
const content = editorState.getCurrentContent()
const html = stateToHTML(content, { inlineStyles })

But then, when I do:

import { stateFromHTML } from 'draft-js-import-html'

EditorState.createWithContent(stateFromHTML("<p><span style="font-size: 34px">yo</span></p> "))

I lose the font-size. Any hints? Thanks a lot!

betancourtl commented 6 years ago

That is a good question, I don't have an answer for you right now but I will look into it and see of that would be possible. It would really be a nice to be able to import html -> draft-js and keep the styles consistent.

rpellerin commented 6 years ago

Thanks!

aamirbhat commented 6 years ago

When this issue will be fixed?

betancourtl commented 6 years ago

@aamirbhat I am not doing any type of development with draft-js , or any draft-js library. If you would like to add an additional feature please submit a PR with tests and I will gladly take a look at it and merge it.

betancourtl commented 5 years ago

I have the functionality for this issue working but It depends on having a PR to draft-js-utils accepted. https://github.com/sstur/draft-js-utils/pull/155

tioluwani94 commented 1 year ago

I was able to resolve this using the draft-convert package, here's a snippet of the code

import { convertFromHTML } from 'draft-convert';

export const convertHTMLToDraft = (htmlText: string) => {
  const contentState = convertFromHTML({
    htmlToStyle: (nodeName, node, currentStyle) => {
      let style = currentStyle;
      if (nodeName === 'span' && node.style.fontFamily) {
        style = style.add(`CUSTOM_FONT_FAMILY_${node.style.fontFamily}`);
      }
      if (nodeName === 'span' && node.style.fontSize) {
        style = style.add(`CUSTOM_FONT_SIZE_${node.style.fontSize}`);
      }
      return style;
    },
  })(htmlText);
  return contentState;
};

I hope this is helpful.