kadikraman / draftjs-md-converter

Converts content from Draft.js blocks to Markdown and vice versa.
https://kadikraman.github.io/draftjs-md-converter/
MIT License
145 stars 37 forks source link

draftjsToMd errors when pasting rich text from an email (1 example) #26

Closed nuclearspike closed 6 years ago

nuclearspike commented 6 years ago

I'm not sure exactly what caused it, but I kind of wonder if a change to Chrome caused this because all of this code used to work perfectly for us. But now when users paste in text from an email, it keeps inline styles that aren't in the default style dict and this package's code doesn't know how to handle that. It'll post inline styles of rgb(192,blah,blah) and background colors when the only ones in the dict are BOLD and ITALIC.

The problem happens in the package code here:

// add the symbol to the md string and push the style in the applied styles stack
      stylesStartAtChar.forEach(function (currentStyle) {
        var symbolLength = markdownDict[currentStyle.style].length;  /// <====the problem
        newText += markdownDict[currentStyle.style];
        totalOffset += symbolLength;
        appliedStyles.push({
          symbol: markdownDict[currentStyle.style],

Since currentStyle.style is either some rgb value or background color, those are not listed in the markdownDict so ".length" is being called on an undefined value.

My temporary work-around to is to just remove anything not in the default dict.

const raw = convertToRaw(editorState.getCurrentContent());
    raw.blocks.forEach((block) => {
      block.inlineStyleRanges.forEach((style) => {
        if (style !== 'BOLD' || style !== 'ITALIC') {
          delete block.inlineStyleRanges[style]
        }
      })
    })
    const markdown = draftjsToMd(raw);

And this fixed it for now. The package needs to be able to just ignore any styles it doesn't recognize.

kadikraman commented 6 years ago

Ah an edge case. Love a good edge case. Thanks for reporting this. I'll get it fixed soon. 😊

kadikraman commented 6 years ago

Just published a new version with this fix:0.1.6 🎉

nuclearspike commented 6 years ago

Excellent! Thanks for the lightning fast turnaround!

kadikraman commented 6 years ago

No worries. Thanks for the super detailed bug report that made it nearly effortless to fix 😊