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

Images not copied in by default. #48

Open joshpitzalis opened 5 years ago

joshpitzalis commented 5 years ago

If I copy and paste this diagram from this link https://gmatclub.com/forum/in-the-figure-shown-what-is-the-value-of-v-x-y-z-w-134894.html into the editor I just get a little glyph of a camera when I convert to markdown, instead of a reference to the image.

joshpitzalis commented 5 years ago

Inspecting the content state, it seems that the block in question gets stored as an unstyled string.

{
      "key": "61jbq",
      "text": "📷\n",
      "type": "unstyled",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": [
        {
          "offset": 0,
          "length": 1,
          "key": 0
        }
      ],
      "data": {}
    }

To get around this, I mapped over the blocks to change any block with entity Range to an atomic type

 const contentState = convertToRaw(editorState.getCurrentContent());
 const blocks = contentState.blocks.map(block => block.entityRanges.length > 0 ? { ...block, "type": "atomic" } : block)
 const mappedContentState = { ...contentState, blocks }
 const markdown = draftjsToMd(mappedContentState);

It works for now.

Is there a better way to do this? Am I going to run into problems with this approach?

kadikraman commented 5 years ago

It may potentially it may result in some unexpected behaviour overriding other types.

An update to this function should be able to provide a general solution. Could you log out node and blockStyles at this point to see if there's any arguments we could leverage?

alexis-judi commented 11 months ago

This is an old bug but this code in my system seemed to do the trick:

 getContentAsMarkDown(editorState) {
    const contentState = convertToRaw(editorState.getCurrentContent());
    const blocks = contentState.blocks.map((block) => {
      if (block.entityRanges.length > 0) {
        const hasImageEntity =
          block.entityRanges.find(
            (entityRange) =>
              contentState.entityMap[entityRange.key].type === 'IMAGE',
          ) !== undefined;
        return hasImageEntity ? { ...block, type: 'atomic' } : block;
      }
      return block;
    });
    const mappedContentState = { ...contentState, blocks };
    return draftjsToMd(mappedContentState);
  }

All the extra code is just a more specific way of ensuring we have the correct block that contains an image entity.