debounce markdown editor change handler

This commit is contained in:
Shawn Erquhart 2017-08-31 21:25:44 -04:00
parent 4821959951
commit c25a7c4abb
2 changed files with 8 additions and 3 deletions

View File

@ -1,5 +1,6 @@
import React, { PropTypes } from 'react'; import React, { PropTypes } from 'react';
import { Editor as Slate, Plain } from 'slate'; import { Editor as Slate, Plain } from 'slate';
import { debounce } from 'lodash';
import Toolbar from '../Toolbar/Toolbar'; import Toolbar from '../Toolbar/Toolbar';
import { Sticky } from '../../../../UI/Sticky/Sticky'; import { Sticky } from '../../../../UI/Sticky/Sticky';
import styles from './index.css'; import styles from './index.css';
@ -20,13 +21,15 @@ export default class RawEditor extends React.Component {
this.setState({ editorState }); this.setState({ editorState });
} }
onChange = debounce(this.props.onChange, 250);
/** /**
* When the document value changes, serialize from Slate's AST back to plain * When the document value changes, serialize from Slate's AST back to plain
* text (which is Markdown) and pass that up as the new value. * text (which is Markdown) and pass that up as the new value.
*/ */
handleDocumentChange = (doc, editorState) => { handleDocumentChange = (doc, editorState) => {
const value = Plain.serialize(editorState); const value = Plain.serialize(editorState);
this.props.onChange(value); this.onChange(value);
}; };
/** /**

View File

@ -1,5 +1,5 @@
import React, { Component, PropTypes } from 'react'; import React, { Component, PropTypes } from 'react';
import { get, isEmpty } from 'lodash'; import { get, isEmpty, debounce } from 'lodash';
import { Editor as Slate, Raw, Block, Text } from 'slate'; import { Editor as Slate, Raw, Block, Text } from 'slate';
import { slateToMarkdown, markdownToSlate, htmlToSlate } from '../../serializers'; import { slateToMarkdown, markdownToSlate, htmlToSlate } from '../../serializers';
import registry from '../../../../../lib/registry'; import registry from '../../../../../lib/registry';
@ -43,11 +43,13 @@ export default class Editor extends Component {
return state.transform().insertFragment(doc).apply(); return state.transform().insertFragment(doc).apply();
} }
onChange = debounce(this.props.onChange, 250);
handleDocumentChange = (doc, editorState) => { handleDocumentChange = (doc, editorState) => {
const raw = Raw.serialize(editorState, { terse: true }); const raw = Raw.serialize(editorState, { terse: true });
const plugins = this.state.shortcodePlugins; const plugins = this.state.shortcodePlugins;
const markdown = slateToMarkdown(raw, plugins); const markdown = slateToMarkdown(raw, plugins);
this.props.onChange(markdown); this.onChange(markdown);
}; };
hasMark = type => this.state.editorState.marks.some(mark => mark.type === type); hasMark = type => this.state.editorState.marks.some(mark => mark.type === type);