import * as React from 'react' import { EditorState, RichUtils } from 'draft-js' import { convertFromHTML, convertToHTML } from 'draft-convert' import { Editor as DraftEditor, KeyCommandController, compose } from 'draft-extend' import * as cx from 'classnames' import { debounce } from 'lodash' import LinkPlugin from './plugins/link' import ImagePlugin from './plugins/image' import ParagraphPlugin from './plugins/paragraph' import 'draft-js/dist/Draft.css' import './style.styl' const plugins = compose(LinkPlugin, ImagePlugin, ParagraphPlugin) const WithPlugins = plugins(DraftEditor) const toHTML = plugins(convertToHTML) const fromHTML = plugins(convertFromHTML) class Editor extends React.Component { constructor(props: any) { super(props) const contentState = fromHTML(props.value) this.state = { editorState: EditorState.createWithContent(contentState), } } handleOutgoingChange = debounce(() => { const value = toHTML(this.state.editorState.getCurrentContent()) .replace(/"/g, '"') // escape jinja values .replace(/'/g, `'`) // escape jinja values .replace(/</g, '<') // escape jinja values .replace(/>/g, '>') // escape jinja values .replace(/
<\/div>/g, '
') // replace empty blocks with empty lines this.props.onChange(this.state.editorState.getCurrentContent().hasText() ? value : '') }, 400) editorStateChanged(oldState: any, newState: any) { return oldState.getCurrentContent() !== newState.getCurrentContent() } handleChange = (editorState: any) => { const didContentChange = this.editorStateChanged(this.state.editorState, editorState) this.setState({ editorState }, didContentChange ? this.handleOutgoingChange : null) } handleKeyCommand = (command: any, editorState: any) => { const newState = RichUtils.handleKeyCommand(editorState, command) if (newState) { this.handleChange(newState) return 'handled' } return 'not-handled' } render() { const { editorState } = this.state const { className, popoverAnchorBottom, removeKeyCommandListener, noPersonalization, addKeyCommandListener, enableDynamicCalendarLink } = this.props return (
) } } export default KeyCommandController(Editor)