draft-js#convertFromHTML JavaScript Examples

The following examples show how to use draft-js#convertFromHTML. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: customHTML2Content.js    From spring-boot-ecommerce with Apache License 2.0 5 votes vote down vote up
// takes HTML string and returns DraftJS ContentState
export default function customHTML2Content(HTML, contentState) {
    var tempDoc = new DOMParser().parseFromString(HTML, 'text/html');
    // replace all <img /> with <blockquote /> elements
    toArray(tempDoc.querySelectorAll('img')).forEach(imgReplacer);
    // use DraftJS converter to do initial conversion. I don't provide DOMBuilder and
    // blockRenderMap arguments here since it should fall back to its default ones, which are fine

    var _convertFromHTML = convertFromHTML(tempDoc.body.innerHTML),
        contentBlocks = _convertFromHTML.contentBlocks;
    // now replace <blockquote /> ContentBlocks with 'atomic' ones


    contentBlocks = contentBlocks.reduce(function (contentBlocks, block) {
        if (block.getType() !== 'blockquote') {
            return contentBlocks.concat(block);
        }
        var image = JSON.parse(block.getText());
        contentState.createEntity('IMAGE-ENTITY', 'IMMUTABLE', image);
        var entityKey = contentState.getLastCreatedEntityKey();
        var charData = CharacterMetadata.create({ entity: entityKey });
        // const blockSpec = Object.assign({ type: 'atomic', text: ' ' }, { entityData })
        // const atomicBlock = createContentBlock(blockSpec)
        // const spacerBlock = createContentBlock({});
        var fragmentArray = [new ContentBlock({
            key: genKey(),
            type: 'image-block',
            text: ' ',
            characterList: List(Repeat(charData, charData.count()))
        }), new ContentBlock({
            key: genKey(),
            type: 'unstyled',
            text: '',
            characterList: List()
        })];
        return contentBlocks.concat(fragmentArray);
    }, []);
    // console.log('>> customHTML2Content contentBlocks', contentBlocks);
    tempDoc = null;
    return BlockMapBuilder.createFromArray(contentBlocks);
}