Home Reference Source

application/util/rawToHtml.js

import React from 'react';
import _ from 'lodash';

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

import RichEditor from './../components/common/rich-editor';
import {ALIGNMENT_DATA_KEY} from './../components/common/rich-editor/libs/extend-rich-utils';
import SimpleEditor from './../components/common/simple-editor';


export const rawToHtml = (contentState) => {
    let html = stateToHTML(contentState, {
        blockRenderers: {
            atomic: (block) => {
                let data = contentState.getEntity(block.getEntityAt(0)).getData();
                const {customType} = data;
                if (customType == 'pull-quote') {
                    const {content, credit} = data;
                    return '<div class="article-embed pull-quote"><div class="pull-quote-body">&ldquo;' + content + '&rdquo;</div><hr><span class="pull-quote-byline">' + credit + '</span></div>';
                } else if (customType == 'horizontal-rule') {
                    return '<hr />';
                } else if (customType == 'embed') {
                    const {content} = data;
                    return '<div class="embed">' + content + '</div>';
                } else if (customType == 'media') {
                    const {height, width, align, mediaUuid, origSrc, linkTo} = data;
                    return '<img class="media-embed" data-embedded-media="' + mediaUuid + '" data-uuid="' + mediaUuid + '" data-link-to="' + linkTo + '" src="' + origSrc + '" data-width="' + width + '" data-height="' + height + '" data-align="' + align + '" />';
                }
            }
        },
        blockStyleFn: (block) => {
            const alignKey = block.getData().get(ALIGNMENT_DATA_KEY);
            if (alignKey) {
                return {
                    attributes: {
                        'class': 'text-align-' + alignKey.toLowerCase()
                    }
                };
            }
        },
        entityStyleFn: (entity) => {
            if (entity && entity.getType() === 'DROPCAP') {
                return {
                    element: 'span',
                    attributes: {
                        'class': 'drop-cap'
                    }
                };
            }
        }
    });

    let parts = html.split(/\n/);
    if (parts.length) {
        if (parts[0] == '<p><br></p>') {
            parts.shift()
        }
        if (parts[parts.length-1] == '<p><br></p>') {
            parts.pop();
        }

        html = parts.join("\n");
    }

    // console.log(html);

    return html;
};