2016-05-27 12:45:55 +08:00
|
|
|
import {Editor, ContentState, convertFromHTML, DefaultDraftBlockRenderMap, DefaultDraftInlineStyle} from 'draft-js';
|
|
|
|
const ReactDOM = require('react-dom');
|
|
|
|
|
2016-05-28 14:28:22 +08:00
|
|
|
const BLOCK_RENDER_MAP = DefaultDraftBlockRenderMap.set('unstyled', {
|
|
|
|
element: 'p' // draft uses <div> by default which we don't really like
|
|
|
|
});
|
|
|
|
|
2016-05-27 12:45:55 +08:00
|
|
|
const styles = {
|
|
|
|
BOLD: 'strong',
|
|
|
|
CODE: 'code',
|
|
|
|
ITALIC: 'em',
|
|
|
|
STRIKETHROUGH: 's',
|
|
|
|
UNDERLINE: 'u'
|
|
|
|
};
|
|
|
|
|
|
|
|
export function contentStateToHTML(contentState:ContentState): String {
|
|
|
|
const elem = contentState.getBlockMap().map((block) => {
|
2016-05-28 14:28:22 +08:00
|
|
|
const elem = BLOCK_RENDER_MAP.get(block.getType()).element;
|
2016-05-27 12:45:55 +08:00
|
|
|
const content = [];
|
|
|
|
block.findStyleRanges(() => true, (s, e) => {
|
|
|
|
const tags = block.getInlineStyleAt(s).map(style => styles[style]);
|
|
|
|
const open = tags.map(tag => `<${tag}>`).join('');
|
|
|
|
const close = tags.map(tag => `</${tag}>`).reverse().join('');
|
|
|
|
content.push(`${open}${block.getText().substring(s, e)}${close}`);
|
|
|
|
});
|
|
|
|
|
2016-05-28 14:28:22 +08:00
|
|
|
return (`<${elem}>${content.join('')}</${elem}>`);
|
2016-05-27 12:45:55 +08:00
|
|
|
}).join('');
|
|
|
|
|
|
|
|
return elem;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function HTMLtoContentState(html:String): ContentState {
|
|
|
|
return ContentState.createFromBlockArray(convertFromHTML(html));
|
|
|
|
}
|