static-cms/src/components/Widgets/MarkdownControl.js

46 lines
1.2 KiB
JavaScript
Raw Normal View History

import React, { PropTypes } from 'react';
import { Editor, EditorState, RichUtils } from 'draft-js';
import { stateToMarkdown } from 'draft-js-export-markdown';
import { stateFromMarkdown } from 'draft-js-import-markdown';
2016-05-30 16:55:32 -07:00
export default class MarkdownControl extends React.Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createWithContent(stateFromMarkdown(props.value || ''))
};
this.handleChange = this.handleChange.bind(this);
this.handleKeyCommand = this.handleKeyCommand.bind(this);
}
handleChange(editorState) {
const content = editorState.getCurrentContent();
this.setState({ editorState });
2016-05-30 16:55:32 -07:00
this.props.onChange(stateToMarkdown(content));
}
handleKeyCommand(command) {
const newState = RichUtils.handleKeyCommand(this.state.editorState, command);
if (newState) {
this.handleChange(newState);
return true;
}
return false;
}
render() {
const { editorState } = this.state;
2016-05-30 16:55:32 -07:00
return (
<Editor
editorState={editorState}
onChange={this.handleChange}
handleKeyCommand={this.handleKeyCommand}
/>);
}
}
MarkdownControl.propTypes = {
onChange: PropTypes.func.isRequired,
value: PropTypes.node,
};